0

我有以下一段 SQL,它返回两个日期之间的所有不同日期。

SELECT DISTINCT convert(char(10), date, 120) as StartDate from table1 WHERE  
id = @id and date > @StartDate

但是我需要返回两个日期之间的不同日期和时间。

IE

2011-12-18 13:00:00.000

2011-12-18 14:00:00.000

2011-12-18 17:00:00.000

2011-12-19 10:00:00.000

2011-12-19 12:00:00.000

2011-12-19 13:00:00.000

希望有人可以协助更改查询以执行此操作。

4

3 回答 3

2
SELECT DISTINCT DATEADD(HH,DATEDIFF(HH,0,DATE),0) as StartDate 
from table1 
WHERE   id = @id and date > @StartDate 
于 2012-05-15T13:56:54.197 回答
0
declare @myDates table(d datetime);
INSERT INTO @myDates VALUES('2011-12-18 13:00:00.000')
, ('2011-12-18 14:00:00.000')
, ('2011-12-18 17:00:00.000')
, ('2011-12-19 10:00:00.000')
, ('2011-12-19 12:00:00.000')
, ('2011-12-19 13:00:00.000');

; WITH a AS (
    SELECT d, r=ROW_NUMBER()OVER(ORDER BY d)
    FROM @myDates
)
SELECT StartDate=CONVERT(VARCHAR(10),a1.d,120)
, EndDate=CONVERT(VARCHAR(10),a2.d,120)
, HoursDiff=DATEDIFF(hh,a1.d,a2.d)
FROM a a1
INNER JOIN a a2 
  ON a2.r=a1.r+1 
  AND CONVERT(VARCHAR(10),a1.d,120)<>CONVERT(VARCHAR(10),a2.d,120);

结果:

StartDate  EndDate    HoursDiff
---------- ---------- -----------
2011-12-18 2011-12-19 17
于 2012-05-15T14:03:45.157 回答
0

我会做以下事情:

SELECT DISTINCT left(convert(varchar, date, 120), 13) as starthour
from table
WHERE   id = @id and date > @StartDate

您还可以使用 SQL Server 中的 datepart() 函数得出类似的结果。在其他数据库中,最好使用 extract(from)。

于 2012-05-15T13:58:45.693 回答