簡體   English   中英

選擇1到n,比較Mysql中每一個的倒數第二行

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

我想提取倒數第​​二位倒數第二位創建於2016年的醫生

醫生

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

耐心

| 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 |

因此,結果必須是Ryan(1)和Harry(4),因為:

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

演示

首先,您使用變量將位置分配給每個患者。

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

然后將其用作子查詢以獲取倒數第二個患者並測試年份。

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

最后加入回到醫生的名字

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; 

輸出:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM