提前感谢你花时间看这个。
我希望获取一些包含日期字段的记录,并将它们分成小时列,每个列都有一个计数(sql server)。
E.g。
SpecialDateColumn
14/1/15 10:23
14/1/15 11:34
14/1/15 12:45
14/1/15 12:55
我在一行中查看结果如下:
Date 10 11 12 13 etc
14/1/15 1 1 2 0
我尝试使用数据透视表来做到这一点,但没有太多的快乐。
提前再次感谢。
答案 0 :(得分:1)
将其写为条件聚合很简单:
select cast(SpecialDateColumn as date) as thedate,
sum(case when datepart(hour, SpecialDateColumn) = 10 then 1 else 0 end) as hour_10,
sum(case when datepart(hour, SpecialDateColumn) = 11 then 1 else 0 end) as hour_11,
sum(case when datepart(hour, SpecialDateColumn) = 12 then 1 else 0 end) as hour_12,
sum(case when datepart(hour, SpecialDateColumn) = 13 then 1 else 0 end) as hour_13
from table t
group by cast(SpecialDateColumn as date)
order by thedate;
答案 1 :(得分:1)
你可以这样做:
SELECT *
FROM (
SELECT SpecialDateColumn AS [Date]
,DATEPART(HOUR, SpecialDateColumn) [Hour]
FROM < TABLE >
) AL1
PIVOT(COUNT([Hour]) FOR [Hour] IN (
[0]
,[1]
,[2]
,[3]
,[4]
,[5]
,[6]
,[7]
,[8]
,[9]
,[10]
,[11]
,[12]
,[13]
,[14]
,[15]
,[16]
,[17]
,[18]
,[19]
,[20]
,[21]
,[22]
,[23]
)) P;
答案 2 :(得分:0)
这种方式总能获得所有时间,但是PIVOT就是一个例子。除此之外,您可以使用动态SQL构建PIVOT,或者使用像Gordon的示例或PIVOT
这样的CASESselect
*
from (
select
CONVERT(DATE,h) D,
DATEPART(HOUR,h) H
from (
select
'2014-01-01 10:00:01' h
UNION ALL
select
'2014-01-02 11:00:01'
UNION ALL
select
'2014-01-03 10:00:01'
UNION ALL
select
'2014-01-03 14:00:01'
) T
) SRC
PIVOT(
COUNT(H)
FOR H IN ([0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23])
) PVT
答案 3 :(得分:0)
Pivot是正确的方式imho ...在下面的代码片段中我有一个带有字段的图像表created_date
select
*
from
(
select
1 as dummy ,
datepart(hh, created_date) as h ,
cast(created_date as date) as d
from images
) as t
pivot( count(t.dummy) for t.h in ([9],[10],[11],[12]) ) as pvt
来自查询的结果看起来像这样: