我需要对每个person_id列进行排序,其中顺序优先级为:
因此,根据数据:
+----+-----------+------+------------+------------+--------+
| id | person_id | type | date_start | date_end | actual |
+----+-----------+------+------------+------------+--------+
| 1 | 1 | Reg | 01-01-2018 | 31-01-2018 | 0 |
+----+-----------+------+------------+------------+--------+
| 2 | 1 | Con | 01-02-2019 | 01-05-2019 | 0 |
+----+-----------+------+------------+------------+--------+
| 3 | 2 | Reg | 01-01-2018 | 31-05-2018 | 0 |
+----+-----------+------+------------+------------+--------+
| 4 | 2 | Reg | 01-05-2018 | 31-07-2019 | 1 |
+----+-----------+------+------------+------------+--------+
| 5 | 2 | Con | 01-06-2018 | 31-04-2020 | 1 |
+----+-----------+------+------------+------------+--------+
| 6 | 2 | Zee | 31-05-2019 | 31-08-2019 | 1 |
+----+-----------+------+------------+------------+--------+
我需要查询有关person_id = 1的结果:
+----+-----------+------+------------+------------+--------+
| id | person_id | type | date_start | date_end | actual |
+----+-----------+------+------------+------------+--------+
| 1 | 1 | Reg | 01-01-2018 | 31-01-2018 | 0 |
+----+-----------+------+------------+------------+--------+
| 2 | 1 | Con | 01-02-2019 | 01-05-2019 | 0 |
+----+-----------+------+------------+------------+--------+
对于person_id = 2,结果为:
+----+-----------+------+------------+------------+--------+
| id | person_id | type | date_start | date_end | actual |
+----+-----------+------+------------+------------+--------+
| 4 | 2 | Reg | 01-05-2018 | 31-07-2019 | 1 |
+----+-----------+------+------------+------------+--------+
| 6 | 2 | Zee | 31-05-2019 | 31-08-2019 | 1 |
+----+-----------+------+------------+------------+--------+
| 5 | 2 | Con | 01-06-2018 | 31-04-2020 | 1 |
+----+-----------+------+------------+------------+--------+
| 3 | 2 | Reg | 01-01-2018 | 31-05-2018 | 0 |
+----+-----------+------+------------+------------+--------+
(此外,这是一个附加的问题,我需要从查询中获取最旧的start_date,但仅在各行之间保持日期连续性的情况下)
答案 0 :(得分:1)
您可以使用CASE
表达式添加特定的权重:
ORDER BY actual DESC, CASE WHEN `type` = 'Reg' THEN 1 ELSE 2 END, date_start DESC