计算一天中每个小时的 SQL table 中的不同值
Count distinct values in an SQL table for each hour in a day
我有一个 table 看起来像这样:
ID TimeStamp CarNumber
1 2018 14:05:32 433
2 2018 14:13:52 420
3 2018 14:55:14 433
4 2018 15:12:03 420
5 2018 16:15:55 570
我必须得到一天中每个小时的不同车号的数量,所以我现在做的是运行每个小时单独的命令:
SELECT DISTINCT CarNumber
FROM Cars
WHERE TimeStamp BETWEEN '2018 14:00:00' AND '2018 15:00:00'
有没有办法构建一个 table 来自动在一天中的每个小时执行此操作?预期输出:
Hour NumberOfCars CarNumbers
0 0 0
...
14 2 433, 420
15 1 420
16 1 570
...
您可以按日期和时间汇总:
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;
像下面这样尝试。从日期时间列中提取小时数并按
分组使用
select convert(date,TimeStamp),
DATEPART(HOUR, TimeStamp) ,
count(distinct CarNumber) numofcars
from Cars
group by convert(date,TimeStamp),DATEPART(HOUR, TimeStamp)
我有一个 table 看起来像这样:
ID TimeStamp CarNumber
1 2018 14:05:32 433
2 2018 14:13:52 420
3 2018 14:55:14 433
4 2018 15:12:03 420
5 2018 16:15:55 570
我必须得到一天中每个小时的不同车号的数量,所以我现在做的是运行每个小时单独的命令:
SELECT DISTINCT CarNumber
FROM Cars
WHERE TimeStamp BETWEEN '2018 14:00:00' AND '2018 15:00:00'
有没有办法构建一个 table 来自动在一天中的每个小时执行此操作?预期输出:
Hour NumberOfCars CarNumbers
0 0 0
...
14 2 433, 420
15 1 420
16 1 570
...
您可以按日期和时间汇总:
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;
像下面这样尝试。从日期时间列中提取小时数并按
分组使用 select convert(date,TimeStamp),
DATEPART(HOUR, TimeStamp) ,
count(distinct CarNumber) numofcars
from Cars
group by convert(date,TimeStamp),DATEPART(HOUR, TimeStamp)