SQL在两行中查找有关Person的信息

时间:2015-12-17 11:26:17

标签: sql sql-server database rows

我必须关注名为Data1的数据库

DateOfBooking | Short   |  Long  |  TimeOfBooking  | ID
-------------------------------------------------------
14.06.2016    | KAL     |  blabla| 13:02           | 1
14.06.2016    | DEF     |  del   | 14:02           | 3
14.06.2016    | KAL     |  blabla| 17:34           | 2
14.06.2016    | DOL     |  blub  | 13:02           | 1

我想在13:02发现这个人的身份证是KAL,在13:02找到DOL,但是只有两人都被预订(同时)。

KAL和DOL总是在同一个TimeOfBooking上为一个ID预订,但我无法弄清楚如何获得结果。 我试过了

SELECT DISTINCT Data1.ID
FROM Data1
WHERE (((Data1.Short = 'KAL') AND (Data1.Long Like 'blabla')) 
AND ((((Data1.Short = 'DOL') AND (Data1.Long Like 'blub')))
Group BY Data1.ID

当然这不起作用,因为它只看到一行。有没有办法查看两行并找到相应的ID?

谢谢。

1 个答案:

答案 0 :(得分:1)

一种方法使用聚合,按ID和预订时间 - 然后检查两个short值:

select d.id
from data1 d
where d.short in ('KAL', 'DOL')
group by d.id, d.timeofbooking
having count(distinct d.short) = 2;

如果您想要完整记录,替代方法使用exists,但有点复杂:

select d.*
from data1 d
where (d.short = 'KAL' and
       exists (select 1 from data1 d2
               where d2.id = d.id and
                     d2.timeofbooking = d.timeofbooking and
                     d2.short = 'DOL'
              )
      ) or
      (d.short = 'DOL' and
       exists (select 1 from data1 d2
               where d2.id = d.id and
                     d2.timeofbooking = d.timeofbooking and
                     d2.short = 'KAL'
              )
      );

或者,甚至,使用窗口函数:

select d.*
from (select d.*,
             min(short) over (partition by id, timeofbooking) as minshort,
             max(short) over (partition by id, timeofbooking) as maxshort
      from data1
      where short in ('KAL', 'DOL')
     ) d
where minshort <> maxshort;