在下面的数据中,对于每个事件,我需要选择Date字段等于或大于指定日期的第一行,我需要选择日期是将来最大日期之外的行。指定日期。但是,我不希望返回两个单独的行,而是每个事件一行,其中第一个记录的日期可以标记为StartDate,第二个记录的日期标记为EndDate。这是数据:
表EventDates
ID EventID Date
1 10 2013-12-01
2 10 2013-12-02
3 10 2013-12-03
4 10 2013-12-04
5 11 2013-12-03
6 11 2013-12-04
7 11 2013-12-31
因此,如果我想在2013-12-02之上或之后选择事件,则所选数据将为:
ID EventID Date
2 10 2013-12-02
4 10 2013-12-04
5 11 2013-12-03
7 11 2013-12-31
但我真正想要的是:
ID EventID StartDate EndDate
2 10 2013-12-02 2013-12-04
5 11 2013-12-03 2013-12-31
请注意,ID指的是日期最短的行。
答案 0 :(得分:2)
您是否尝试过使用Aggregate functions?
SELECT MIN(ID) AS ID -- Smallest ID
, EventID -- EventID
, MIN(Date) AS StartDate -- Earliest Date
, MAX(Date) AS EndDate -- Latest Date
FROM table
WHERE Date >= '2013-12-02'
GROUP BY EventID -- From all records that share an EventID
<强>更新强>
如果要返回uniqueidentifier
ID,您应该可以使用子查询:
SELECT table.ID
, aggregates.EventID
, aggregates.StartDate
, aggregates.EndDate
FROM (
SELECT EventID -- EventID
, MIN(Date) AS StartDate -- Earliest Date
, MAX(Date) AS EndDate -- Latest Date
FROM table
WHERE Date >= '2013-12-02'
GROUP BY EventID -- From all records that share an EventID
) AS aggregates
INNER JOIN table
ON table.EventID = aggregates.EventID
AND table.Date = aggregates.StartDate
WHERE Date >= '2013-12-02'