2

我有一个服务器请求表——每个请求都有一个时间戳。我想要完成的是,我的查询结果(或者最好是存储过程)在一天内为我提供了一个表格,其中一天中的每个小时都在顶部(从 0 到 23)和每一分钟小时(从 0 到 59)。相交数据将显示每分钟、每小时的请求数。

到目前为止,我尝试将一天中的分钟分组,并在 excel 中对其进行操作以使用以下方法生成 24x60 矩阵:

SELECT DatePart(HH,Timestamp) as [Hour]
      , DatePart(MI,Timestamp) as [Minute]
    , Count(*) as [Count]

FROM Requests 
WHERE DatePart(Day,Timestamp) = 12

GROUP BY DatePart(HH,Timestamp), 
    DatePart(MI,Timestamp)

ORDER BY DatePart(HH,Timestamp)
    , DatePart(MI,Timestamp)

任何帮助将不胜感激,提前感谢您的时间:)

4

1 回答 1

1

如果您的数据库支持数据透视,则可以缩短。如果在那一分钟内没有数据,它将错过几分钟。

Select
    DatePart(MI,Timestamp) as Mi,
    Sum(Case When DatePart(HH,Timestamp) = 0 Then 1 Else 0 End) as H0,
    Sum(Case When DatePart(HH,Timestamp) = 1 Then 1 Else 0 End) as H1,
    Sum(Case When DatePart(HH,Timestamp) = 2 Then 1 Else 0 End) as H2,
    Sum(Case When DatePart(HH,Timestamp) = 3 Then 1 Else 0 End) as H3,
    Sum(Case When DatePart(HH,Timestamp) = 4 Then 1 Else 0 End) as H4,
    Sum(Case When DatePart(HH,Timestamp) = 5 Then 1 Else 0 End) as H5,
    Sum(Case When DatePart(HH,Timestamp) = 6 Then 1 Else 0 End) as H6,
    Sum(Case When DatePart(HH,Timestamp) = 7 Then 1 Else 0 End) as H7,
    Sum(Case When DatePart(HH,Timestamp) = 8 Then 1 Else 0 End) as H8,
    Sum(Case When DatePart(HH,Timestamp) = 9 Then 1 Else 0 End) as H9,
    Sum(Case When DatePart(HH,Timestamp) = 10 Then 1 Else 0 End) as H10,
    Sum(Case When DatePart(HH,Timestamp) = 11 Then 1 Else 0 End) as H11,
    Sum(Case When DatePart(HH,Timestamp) = 12 Then 1 Else 0 End) as H12,
    Sum(Case When DatePart(HH,Timestamp) = 13 Then 1 Else 0 End) as H13,
    Sum(Case When DatePart(HH,Timestamp) = 14 Then 1 Else 0 End) as H14,
    Sum(Case When DatePart(HH,Timestamp) = 15 Then 1 Else 0 End) as H15,
    Sum(Case When DatePart(HH,Timestamp) = 16 Then 1 Else 0 End) as H16,
    Sum(Case When DatePart(HH,Timestamp) = 17 Then 1 Else 0 End) as H17,
    Sum(Case When DatePart(HH,Timestamp) = 18 Then 1 Else 0 End) as H18,
    Sum(Case When DatePart(HH,Timestamp) = 19 Then 1 Else 0 End) as H19,
    Sum(Case When DatePart(HH,Timestamp) = 20 Then 1 Else 0 End) as H20,
    Sum(Case When DatePart(HH,Timestamp) = 21 Then 1 Else 0 End) as H21,
    Sum(Case When DatePart(HH,Timestamp) = 22 Then 1 Else 0 End) as H22,
    Sum(Case When DatePart(HH,Timestamp) = 23 Then 1 Else 0 End) as H23
From
    Requests
Group By
    DatePart(MI,Timestamp)
Order By
    DatePart(MI,Timestamp)

使用 Pivot 的版本:

Select
    Mi,
    [0],  [1],  [2],  [3],  [4],  [5],  [6],  [7],
    [8],  [9],  [10], [11], [12], [13], [14], [15],
    [16], [17], [18], [19], [20], [21], [22], [23]
From (
    select
        datepart(mi, timestamp) mi,
        datepart(hh, timestamp) hh
    from 
        Requests
    ) as s
Pivot (
    count(hh)
For
    hh 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]
   )
) as p
Order By mi;

示例小提琴

于 2013-09-14T12:31:49.590 回答