sql-server:使用DATEADD()创建3个日期范围

时间:2014-06-13 15:12:42

标签: sql sql-server

我尝试从Time_Stamp MainHospital='Hospital1'创建3个日期范围。 Hospital1在表Survey中的Time_Stamp列中返回这些结果:http://i.imgur.com/mvg9pQu.png

每个日期范围之间需要2天,从最早的日期开始的第一个日期范围。我还试图将日期格式化为YYYY-MM-DD,而没有时间限制。

获得最早的日期:

SELECT min(Time_Stamp)
FROM Survey
WHERE MainHospital = 'Hospital1'

增加2天(但不显示范围)

SELECT DATEADD(day,2,Time_Stamp)
FROM Survey
WHERE MainHospital = 'Hospital1'

上面的imgur链接结果的确切结果。假设它需要一个" - "分隔符

1    2014-01-27 - 2014-01-29

2    2014-01-30 - 2014-02-01

3    2014-02-02 - 2014-02-04

1 个答案:

答案 0 :(得分:0)

首先,我不建议您格式化输出,直到到达表示层。这是一个坏习惯。话虽如此,我认为这个查询会这样做:

SELECT id, 
       MIN(Time_Stamp) as start, 
       DATEADD(day, 2, MIN(Time_Stamp)) as end
FROM Survey
WHERE MainHospital = 'Hospital1'
GROUP BY Id

更新:

如果您只想根据原始行选择接下来的两行,请尝试以下方法:

with start as
(
    SELECT id, 
           MIN(Time_Stamp) as startDate, 
           DATEADD(day, 2, MIN(Time_Stamp)) as endDate
    FROM Survey
    WHERE MainHospital = 'Hospital1'
    GROUP BY Id
),
results as
(

   SELECT startDate, endDate from start
   union
   SELECT DATEADD(DAY, 1, endDate), DATEADD(day, 3, endDate) FROM start
   UNION
   SELECT DATEADD(DAY, 4, endDate), DATEADD(day, 6, endDate) FROM start
)
SELECT * FROM results

虽然您可以在SQL中执行上述操作,但如果您可以选择在表示层上执行此操作,我建议您这样做。这个任务更适合像C#这样的东西。