将日期列拆分为小时段

Split date column into hour segments

预先感谢您抽出宝贵时间查看此内容。

我想获取一些包含日期字段的记录,并将它们分成小时列,每个列都有一个计数(sql 服务器)。

例如

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

我曾尝试使用枢轴 table 来做到这一点,但并没有太大的乐趣。

再次感谢。

将其写成条件聚合就足够简单了:

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;

这种方式总是会得到所有的时间,但它是 PIVOT 的一个例子。除此之外,您可以使用动态 SQL 来构造 PIVOT,或者像 Gordon 的示例或 PIVOT

这样的 CASES
select
    *
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

枢轴是正确的方式恕我直言......在下面的代码片段中,我有一个图像 Table 和一个字段 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

查询结果看起来是这样的:

你可以这样做:

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;