我有一个服务器,其中包含一列仅包含日期(日期时间),另一列仅包含时间(字符),但我尝试使用下面的代码创建每小时计数,但它没有按预期显示:
SELECT
account_date as Date,
sum(qty) as qty
sum(amount) as Amount,
cast(datepart(hour,time) as varchar)
FROM [data source]
WHERE account_date between '10/1/2022' and '10/5/2022'
GROUP BY account_date, time
我期待这样的事情:
以下是日期和时间列的数据格式:
**Date**
2022-10-01 00:00:00.000
2022-10-02 00:00:00.000
2022-10-03 00:00:00.000
2022-10-04 00:00:00.000
**Time**
0709
0707
0707
0707
您正在寻找条件聚合或数据透视表。
Select account_date
,[0000] = sum(case when left([Time],2)='00' then qty else 0 end)
,[0100] = sum(case when left([Time],2)='01' then qty else 0 end)
,[0200] = sum(case when left([Time],2)='02' then qty else 0 end)
-- ... add more columns
,[2300] = sum(case when left([Time],2)='23' then qty else 0 end)
From YourTable
Where account_date between '2022-10-01' and '2022-10-05'
Group By account_date