2016-02-16 54 views
0

基本的SQL問題,但我有一個空白的頭腦。我有以下設置的表:SQL Server查詢返回一個事件的下一個日期

date   eventType 
----------------------- 
01/01/2016 0 
02/01/2016 0 
03/01/2016 2 
03/01/2016 2 
04/01/2016 6 
04/01/2016 6 
04/01/2016 6 
04/01/2016 6 
05/01/2016 0 
06/01/2016 ... 

我想回到「下一個事件集,其中EVENTTYPE <> 0」

所以,如果「今天」是2016年1月1日時,查詢將返回:

03/01/2016  2 
03/01/2016  2 

如果 「今天」 是2016年3月1日,該查詢將返回:

04/01/2016  6 
04/01/2016  6 
04/01/2016  6 
04/01/2016  6 

Ë tc。

非常感謝

回答

0

我有一個不同的s解決方案,檢查此:

DECLARE @dtEventType DATE = '20160101' 

DECLARE @table TABLE (cDate DATE , eventType TINYINT) 

INSERT INTO @table 
VALUES('20160101' , 0) 
, ('20160102' , 0) 
, ('20160103' , 2) 
, ('20160103' , 2) 
, ('20160104' , 6) 
, ('20160104' , 6) 
, ('20160104' , 6) 
, ('20160104' , 6) 
, ('20160105' , 0) 

SELECT * 
FROM @table L 
WHERE cDate = ( 
    SELECT MIN(cDate) AS mnDate 
    FROM @table 
    WHERE eventType <> 0 
    AND cDate > @dtEventType 
) 

但我喜歡@ GordonLiff的第三個解決方案。

+0

這對我很好,謝謝。這是'WHERE date =(SELECT ...)'我以後。感謝您修復思維障礙 – Jammo

1

嗯。我認爲這可能比看起來有點棘手。這你想要做什麼的問題的數據:

select e.* 
from events e cross join 
    (select top 1 eventType 
     from events 
     where date > getdate() and eventType <> 0 
     order by date 
    ) as nexte 
where e.date > getdate() and 
     e.eventType = nexte.eventType; 

或者,也許更適合:

select e.* 
from events e cross join 
    (select top (1) e.* 
     from events 
     where date > getdate() and eventType <> 0 
     order by date 
    ) as nexte 
where e.date > nexte.date and 
     e.eventType = nexte.eventType; 

或者更簡單地說:

select top (1) with ties e.* 
from events e 
where date > getdate() and eventType <> 0 
order by date, eventType 
+0

我想限制交叉連接,因爲數據集很大,但是,您的第三個解決方案只會返回一條記錄,不是嗎? – Jammo

+0

這是錯誤的,「WITH TIES可能會導致返回的行數多於expression中指定的值」,請檢查TOP子句的WITH TIES選項。 https://msdn.microsoft.com/en-us/library/ms189463.aspx – chancrovsky

+0

我從來不知道'WITH TIES'。我使用@ chancrovsky的解決方案,但提示爲+1。乾杯 – Jammo

0

也許這將工作:

SELECT eventDate, event 
FROM events 
WHERE eventDayte > GETDATE()+1 -- limit here to datePart date to avoid confusion with time as this can lead to issues 
-- we should provide limit here to avoid return all future events 
AND eventDate <= GETDATE()+2 
AND eventType<>0