简体   繁体   English

选择1到n,比较Mysql中每一个的倒数第二行

[英]Select in 1 to n comparing the second last row of each one in Mysql

I would like to extract the doctors for whom their penultimate patient in reverse creation order was created in 2016 我想提取倒数第​​二位倒数第二位创建于2016年的医生

DOCTORS 医生

| id |  name  |
|  1 |  Ryan  |
|  2 |  Pete  |
|  3 |  Anna  |
|  4 |  Harry |

PATIENTS 耐心

| id |  name  | surgeon_id | created_at |
|  1 | Gloria |     1      | 2016-05-01 |
|  2 | Bob    |     1      | 2016-06-21 |
|  3 | Alex   |     2      | 2015-05-01 |
|  4 | Jim    |     2      | 2016-05-01 |
|  3 | Kay    |     3      | 2016-05-01 |
|  5 | Kim    |     4      | 2016-05-01 |
|  6 | Joe    |     4      | 2017-01-03 |

So the result must be Ryan(1) and Harry(4) because of: 因此,结果必须是Ryan(1)和Harry(4),因为:

|  1 | Gloria |     1      | 2016-05-01 |
|  5 | Kim    |     4      | 2016-05-01 |

DEMO 演示

First you use variable to assign a position to each patient. 首先,您使用变量将位置分配给每个患者。

SELECT `id`, `name`, `surgeon_id`, `created_at`,
       @pos := IF(@surgeon_id = surgeon_id, 
                  @pos + 1, 
                  IF(@surgeon_id := surgeon_id, 1, 1) 
                 ) as rn
FROM Table1
CROSS JOIN (SELECT @pos := 0, @surgeon_id :=0 ) as parameters
ORDER BY `surgeon_id`, `created_at` DESC

Then use that as a subquery to get the second to last patient and test the year. 然后将其用作子查询以获取倒数第二个患者并测试年份。

SELECT `id`, `name`, `surgeon_id`, `created_at`
FROM (
        SELECT `id`, `name`, `surgeon_id`, `created_at`,
               @pos := IF(@surgeon_id = surgeon_id, 
                          @pos + 1, 
                          IF(@surgeon_id := surgeon_id, 1, 1) 
                         ) as rn
        FROM Table1
        CROSS JOIN (SELECT @pos := 0, @surgeon_id :=0 ) as parameters
        ORDER BY `surgeon_id`, `created_at` DESC
     ) T
WHERE T.rn = 2
  AND YEAR(`created_at`) = 2016

Finally Join back to Doctors to get the name 最后加入回到医生的名字

SELECT Doctors.`id`, Doctors.`name`
FROM (
        SELECT `id`, `name`, `surgeon_id`, `created_at`,
               @pos := IF(@surgeon_id = surgeon_id, 
                          @pos + 1, 
                          IF(@surgeon_id := surgeon_id, 1, 1) 
                         ) as rn
        FROM Patients
        CROSS JOIN (SELECT @pos := 0, @surgeon_id :=0 ) as parameters
        ORDER BY `surgeon_id`, `created_at` DESC
     ) T
JOIN Doctors
  ON T.`surgeon_id` = Doctors.`id`
WHERE T.rn = 2
  AND YEAR(`created_at`) = 2016; 

OUPUT: 输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM