基本的SQL问题,但我有一个空白。我有一个表格,其中包含以下设置:
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"
所以,如果"今天"是01/01/2016,查询将返回:
03/01/2016 2
03/01/2016 2
如果"今天"是03/01/2016,查询将返回:
04/01/2016 6
04/01/2016 6
04/01/2016 6
04/01/2016 6
等
非常感谢
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:0)
我有一个不同的解决方案,请检查:
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的第三个解决方案。