每天每小时在SQL表中计算不同的值

时间:2018-12-10 12:50:31

标签: sql sql-server-2008

我有一个看起来像这样的表:

ID    TimeStamp    CarNumber
1    2018\12\03 14:05:32    433
2    2018\12\03 14:13:52    420
3    2018\12\03 14:55:14    433
4    2018\12\03 15:12:03    420
5    2018\12\03 16:15:55    570

我必须获取一天中每个小时的不同车号,所以我现在要做的是分别为每个小时运行一个命令:

SELECT DISTINCT CarNumber
FROM Cars
WHERE TimeStamp BETWEEN '2018\12\03 14:00:00' AND '2018\12\03 15:00:00'

有没有一种方法可以建立一个表格,该表格可以在一天的每个小时自动执行此操作?预期输出:

Hour    NumberOfCars    CarNumbers
0       0               0
...
14      2               433, 420
15      1               420
16      1               570
...

2 个答案:

答案 0 :(得分:0)

您可以按日期和小时进行汇总:

select cast(timestamp as date) as thedate,
       datepart(hour, timestamp) as thehour,
       count(distinct CarNumber) as num_cars
from cars
group by cast(timestamp as date), datepart(hour, timestamp)
order by thedate, thehour;

如果只需要一个日期的结果,则可以添加where子句。如果要在几天内汇总结果,请从逻辑中删除thedate

select datepart(hour, timestamp) as thehour,
       count(distinct CarNumber) as num_cars
from cars
group by datepart(hour, timestamp)
order by thehour;

答案 1 :(得分:0)

尝试如下。从日期时间列中提取小时数,并按

分组使用
 select convert(date,TimeStamp),
 DATEPART(HOUR, TimeStamp) ,
 count(distinct CarNumber) numofcars
 from Cars 
 group by convert(date,TimeStamp),DATEPART(HOUR, TimeStamp)