sql - Count distinct values in an SQL table for each hour in a day
问题描述
I have a table that looks like this:
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
I have to get the number of distinct car numbers for each hour of the day, so what I do now is run a command for each hour separately:
SELECT DISTINCT CarNumber
FROM Cars
WHERE TimeStamp BETWEEN '2018\12\03 14:00:00' AND '2018\12\03 15:00:00'
Is there a way to build a table that will do that for each hour of the day automatically? Expected output:
Hour NumberOfCars CarNumbers
0 0 0
...
14 2 433, 420
15 1 420
16 1 570
...
解决方案
You can aggregate by date and hour:
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;
You can add a where
clause if you want the results for only one date. If you want the results aggregated over multiple days, remove thedate
from the logic:
select datepart(hour, timestamp) as thehour,
count(distinct CarNumber) as num_cars
from cars
group by datepart(hour, timestamp)
order by thehour;
推荐阅读
- php - Nginx 在响应数据之前添加来自其缓冲区的发布请求正文内容?
- c++ - Qt Checkable QActions
- reactjs - 嵌套路由和 Material-UI 列表不起作用
- java - 如何使用 Spring Security 和 Vue.js 设置登录?
- typescript - TypeScript 中的递归 AST 访问者
- python - 为什么这些自定义函数在 Python 中打印不同的值?
- javascript - 将参数传递给 JSON 对象中的函数
- jquery - 通过ajax将带有图像和json的Formdata发送到服务器端
- css - 将图像大小调整为 CSS 网格,同时在悬停时进行图像替换
- javascript - 从 JavaScript 中的 2 个不同来源增加一个值