SELECT DISTINCT问题,选择多个预订

时间:2018-08-07 18:39:37

标签: sql-server tsql

我有两个表tblReservationtblBookingtblReservation有一个ID列和一个“事件名称”列。 tblBooking拥有自己的ID列,并且还具有Reservation ID列(外键),然后还有EventStart和EventEnd列。

基本上我正在做以下事情:

SELECT DISTINCT 
    B1.ReservationID,
    B1.EventStart,
    B1.EventEnd,
    tblReservation.EventName
FROM        
    tblBooking AS B1 
INNER JOIN
    tblReservation ON B1.ReservationID = tblReservation.ID
WHERE       
    B1.EventEnd = (SELECT MAX(B2.EventEnd)
                   FROM tblBooking AS B2
                   WHERE B2.ReservationID = B1.ReservationID)

我尝试了此子查询,每次预订仅提取一个预订ID。本质上我想要这些结果:

Reservation ID     EventStart    EventEnd     EventName
1                  1/1/18        1/2/18       Event 1
2                  1/2/18        1/3/18       Event 2 
3                  1/4/18        1/6/18       Event 3

相反,我得到了:

Reservation ID     EventStart    EventEnd     EventName
1                  1/1/18        1/1/18       Event 1
1                  1/2/18        1/2/18       Event 1
2                  1/2/18        1/2/18       Event 2
2                  1/3/18        1/3/18       Event 2 

2 个答案:

答案 0 :(得分:0)

WITH X AS (
SELECT      
       B1.ReservationID
     , B1.EventStart
     , B1.EventEnd
     , tblReservation.EventName
     , ROW_NUMBER() OVER (PARTITION BY B1.ReservationID ORDER BY B1.[EventEnd] DESC) rn
FROM        tblBooking AS B1 
INNER JOIN  tblReservation ON B1.ReservationID = tblReservation.ID
)
SELECT 
       x.ReservationID
     , x.EventStart
     , x.EventEnd
     , x.EventName
FROM X 
WHERE x.rn = 1

答案 1 :(得分:0)

select DISTINCT(B1.ReservationID), MIN(B1.EventStart) as EventStart, MAX(B1.EventEnd) as EventEnd, Res.EventName
from tblBooking B1
left join tblReservation Res on Res.ID = B1.ReservationID
GROUP BY B1.ReservationID, Res.EventName