我得到了以下SQL,它返回了两个日期之间的所有不同日期。
SELECT DISTINCT convert(char(10), date, 120) as StartDate from table1 WHERE
id = @id and date > @StartDate
但是我需要在两个日期之间返回不同的日期和时间。
即
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
希望有人可以协助改变查询来执行此操作。
答案 0 :(得分:2)
SELECT DISTINCT DATEADD(HH,DATEDIFF(HH,0,DATE),0) as StartDate
from table1
WHERE id = @id and date > @StartDate
答案 1 :(得分:0)
我会做以下事情:
SELECT DISTINCT left(convert(varchar, date, 120), 13) as starthour
from table
WHERE id = @id and date > @StartDate
您还可以使用SQL Server中的datepart()函数来提供类似的功能。在其他数据库中,最好使用extract(from)。
答案 2 :(得分: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