【发布时间】:2016-08-07 00:26:16
【问题描述】:
我正在尝试查询具有日期时间“myDateTime”列的表,并获取每个“myDateTime”出现次数的计数,然后将其按“myDateTime”作为日期和当天的小时作为列进行分组.
with CTE1 as (select DATEADD(dd, DATEDIFF(dd, 0, myDateTime), 0) myDate, count(myDateTime) as Counts,
case when DATEPART(hour,(DATEADD(hh, DATEDIFF(hh, 0, myDateTime), 0))) in (0,1,2,3,4,5,6,7,21,22,23) then '8 PM to 7 AM'
when DATEPART(hour,(DATEADD(hh, DATEDIFF(hh, 0, myDateTime), 0))) = 8 then '8 AM'
when DATEPART(hour,(DATEADD(hh, DATEDIFF(hh, 0, myDateTime), 0))) = 9 then '9 AM'
when DATEPART(hour,(DATEADD(hh, DATEDIFF(hh, 0, myDateTime), 0))) = 10 then '10 AM'
when DATEPART(hour,(DATEADD(hh, DATEDIFF(hh, 0, myDateTime), 0))) = 11 then '11 AM'
when DATEPART(hour,(DATEADD(hh, DATEDIFF(hh, 0, myDateTime), 0))) = 12 then '12 PM'
when DATEPART(hour,(DATEADD(hh, DATEDIFF(hh, 0, myDateTime), 0))) = 13 then '1 PM'
when DATEPART(hour,(DATEADD(hh, DATEDIFF(hh, 0, myDateTime), 0))) = 14 then '2 PM'
when DATEPART(hour,(DATEADD(hh, DATEDIFF(hh, 0, myDateTime), 0))) = 15 then '3 PM'
when DATEPART(hour,(DATEADD(hh, DATEDIFF(hh, 0, myDateTime), 0))) = 16 then '4 PM'
when DATEPART(hour,(DATEADD(hh, DATEDIFF(hh, 0, myDateTime), 0))) = 17 then '5 PM'
when DATEPART(hour,(DATEADD(hh, DATEDIFF(hh, 0, myDateTime), 0))) = 18 then '6 PM'
when DATEPART(hour,(DATEADD(hh, DATEDIFF(hh, 0, myDateTime), 0))) = 19 then '7 PM'
when DATEPART(hour,(DATEADD(hh, DATEDIFF(hh, 0, myDateTime), 0))) = 20 then '8 PM'
else 'Error' end as HourOfDay
from [table1] with(nolock)
where myDateTime is not null
and datediff(day, myDateTime, getdate()) <= 10
group by DATEADD(dd, DATEDIFF(dd, 0, myDateTime), 0), DATEPART(hour,(DATEADD(hh, DATEDIFF(hh, 0, myDateTime), 0)))
),
CTE2 as (select myDate, sum(Counts) as Counts, HourOfDay
from CTE1
group by myDate, HourOfDay
--order by HourOfDay desc
)
--CTE3 as (select distinct HourOfDay as hod from cte2)
select myDate, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14]
from CTE2
PIVOT
(
sum(Counts)
for HourOfDay in ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14])
) as piv
不幸的是,我得到的结果到处都是空值。出现 1-14 数字的地方应该是我的上午 8 点到晚上 8 点,以及在该时间范围之外的几个小时的额外列。我究竟做错了什么?
myDate 1 2 3 4 5 6 7 8 9 10 11 12 13 14
2016-04-13 00:00:00.000 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
2016-04-14 00:00:00.000 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
2016-04-15 00:00:00.000 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
【问题讨论】:
标签: sql-server pivot common-table-expression