0
datetime 'myDateTime'列を持つテーブルをクエリし、各 'myDateTime'が何回表示されているかを取得し、 'myDateTime 'を日付として、その日の時間を列として表します。datetime列をピボットし、時刻別に集計するとNULLが返される
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
私が残念ながら得ているのは、すべてがnullです。 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