根据特定条件选择唯一行

时间:2011-03-11 18:13:33

标签: mysql sql

我有一个名为“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  |
+-----+-----------+--------+------------+------------+------------+-------+

我正在寻找一个SQL查询框架,该查询将获取具有唯一开始日期和结束日期的所有行。对于具有重复开始日期和结束日期的行,我需要选择颜色为1或18的行,而不是那些颜色为3的行。

我尝试使用下面的查询,但所选的不同行是ID最低的行

SELECT * FROM trainings GROUP BY StartDate,EndDate

什么是正确的方法?

5 个答案:

答案 0 :(得分:2)

您可以在group byStartDate, 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);

测试数据:

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

答案 1 :(得分:0)

SELECT DISTINCT CONCAT(StartDate, EndDate) FROM trainings

如果我理解得对。

答案 2 :(得分:0)

这是你的意思

SELECT * FROM trainings WHERE color IN (1,18) GROUP BY StartDate,EndDate

答案 3 :(得分:0)

假设StartDate,EndDate和Colors会产生独特的记录......

SELECT * FROM
From Trainings T
(
  SELECT
   StartDate,
   EndDate,
   MAX(CASE WHEN Color = 3 THEN 0 ELSE Color END) Color
  From Trainings
  GROUP By StartDate, EndDate
) T1 on T.StartDate = T1.StartDate AND T.EndDate = T1.EndDate AND T.Color = T1.Color

答案 4 :(得分:0)

您可以这样做:

select 
    t1.*,
    case
        when t2.Id is null then 1
        when t1.color in (1,18) then 2
        else 3
    end as priority
from trainings as t1
left join trainings as t2 on
    t1.StartDate = t2.StartDate and
    t1.EndDate = t2.EndDate and
    t1.Id != t2.Id
order by priority

优先级的值将帮助您找到所需内容:

  • 优先级为1的行具有唯一的开始和结束日期
  • 优先级为2的行有1或18个颜色
  • 所有其他行都具有优先级3