2015-12-17 24 views
0

我有以下稱爲數據1SQL兩行

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 

我想要找的人的ID都是在KAL 13:02和DOL在13:02在那裏預訂數據庫,但查找有關的信息的人只有同時預訂(同時)。

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?

謝謝。

+0

無需既SELECT DISTINCT和GROUP BY在這裏,他們都被刪除重複。 – jarlh

+0

相關提示謝謝。 –

回答

0

不太清楚你問什麼,但是這將返回數據時,KOL和DOL具有相同的ID和時間戳:

select tk.*, td.* 
from (select * from data1 where Short = 'KAL') tk 
join (select * from data1 where Short = 'DOL') td 
    ON tk.id = td.id and tk.TimeOfBooking = td.TimeOfBooking 
+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; 
+0

非常感謝您的許多解決方案!聚合方法在我的數據庫中工作得最快,所以我將使用它並閱讀聚合方法:D –