作者:的士发个火 | 来源:互联网 | 2023-10-11 12:46
IhaveanSQLtablecalledtrainingsthatlookslikethis:我有一个名为“trainings”的SQL表,如下所示:+-----+--
I have an SQL table called "trainings" that looks like this:
我有一个名为“trainings”的SQL表,如下所示:
+-----+-----------+--------+------------+------------+------------+-------+
| Id | Booked |Coach_No| Student_No | StartDate | EndDate | Color |
+-----+-----------+--------+------------+------------+------------+-------+
| 1 | 1 | 20 | NULL | 2011-03-18 |2011-03-19 | 3 |
| 2 | 1 | 20 | 45 | 2011-03-18 |2011-03-19 | 1 |
| 3 | 1 | 15 | 41 | 2011-03-20 |2011-03-21 | 18 |
| 4 | 0 | 21 | NULL | 2011-03-22 |2011-03-23 | 3 |
| 5 | 0 | 33 | NULL | 2011-03-20 |2011-03-21 | 3 |
| 6 | 0 | 34 | NULL | 2011-03-20 |2011-03-21 | 3 |
+-----+-----------+--------+------------+------------+------------+-------+
I'm looking to frame an SQL query that will fetch all the rows with unique start and end dates. For rows with duplicate start and end dates, I need to select those with a color of 1 or 18 in preference over those with a color of 3.
我正在寻找一个SQL查询框架,它将获取具有唯一开始和结束日期的所有行。对于具有重复开始日期和结束日期的行,我需要选择颜色为1或18的颜色优先于颜色为3的颜色。
I've attempted to use the query below, but the distinct row that is selected is the one with the lowest Id
我试图使用下面的查询,但选择的不同行是具有最低Id的行
SELECT * FROM trainings GROUP BY StartDate,EndDate
What is the right approach?
什么是正确的方法?
5 个解决方案
2
You could group by
on StartDate, EndDate
, and select two ID's for the different color priorities. Then join back to the original table, preferring the high priority:
您可以在StartDate,EndDate上进行分组,并为不同的颜色优先级选择两个ID。然后加入到原始表中,优先选择高优先级:
select b1.*
from Trainings b1
join (
select max(case when Color in (1,18) then Id end) as HighPrioID
, max(case when Color not in (1,18) then Id end) as LowPrioID
from Trainings
group by
StartDate
, EndDate
) b2
on b1.Id = COALESCE(b2.HighPrioID, b2.LowPrioID);
Test data:
drop table if exists Trainings;
create table Trainings (id int, StartDate datetime, EndDate datetime, Color int);
insert Trainings values
(1,'2011-03-18','2011-03-19', 3),
(2,'2011-03-18','2011-03-19', 1),
(3,'2011-03-20','2011-03-21',18),
(4,'2011-03-22','2011-03-23', 3),
(5,'2011-03-20','2011-03-21', 3);