我在这里有一列,我需要获取每天的小时数(以后每1小时+1)
预期输出:
Date | HourSpent
2017-12-08 | 6
我的代码尝试:
SELECT Cast(TransDateTime as Date), DateDIFF(hour,MIN(TransDateTime),MAX(TransDateTime)) as DateTime
FROM GuestTransLedger where GuestExtID = '2016-120-5624873'
GROUP BY Cast(TransDateTime as Date) ORDER BY 1 DESC
答案 0 :(得分:3)
尝试一下:
select convert(date, datetime_column) as Date, count(distinct datepart(hour,datetime_column)) as HourSpent
from tbl
group by convert(date, datetime_column)
答案 1 :(得分:1)
在这里日历表方法可能是一个不错的选择:
WITH cte AS (
SELECT '2017-12-08 00:00:00' AS dt UNION ALL
SELECT '2017-12-08 01:00:00' UNION ALL
SELECT '2017-12-08 02:00:00' UNION ALL
...
SELECT '2017-12-08 22:00:00' UNION ALL
SELECT '2017-12-08 23:00:00'
)
SELECT
CONVERT(date, t1.dt) AS Date,
COUNT(DISTINCT t1.dt) AS HoursSpent
FROM cte t1
INNER JOIN yourTable t2
ON t2.DateTime >= t1.dt AND t2.DateTime < DATEADD(HOUR, 1, t1.dt)
GROUP BY
CONVERT(date, t1.dt);
此答案唯一棘手的部分是生成小时日历表。 See here是在SQL Server中执行此操作的一种方法。