T-SQL 为过去 24 小时内的每一小时创建一个数据点

T-SQL to create one data point for each hour over past 24 hours

请问我们该怎么做:

1) 从当前时间向后 24 小时后每小时生成 24 行一行

2) 将过去 24 小时内另一个 table 的数据汇总到这 24 个数据点中。

我看到解决方案建议数字 table 从 0-23,但是如果我们需要从现在开始,然后 运行 回到 24 小时 Get every hour for a time range

例如 [5:00am, 4:00am, 3:00am ... 12:am, 11pm ... 7:00am, 6:00am]

来源Table:

select d,h,count(1)cnt from msgs 
where dt>= DateAdd(hh, -24, sysdatetime()) 
group by d,h order by 1 desc,2 desc

示例数据

d           h   cnt
2015-06-05  16  11
2015-06-05  13  44
2015-06-05  12  16
2015-06-05  11  31
2015-06-05  10  10
2015-06-05  9   12
2015-06-05  8   1
2015-06-04  21  1
2015-06-04  20  2
2015-06-04  18  5
2015-06-04  16  2

我缺少小时数,我需要一个用 0

填充缺少小时数的查询

您可以尝试加入这个功能:

CREATE FUNCTION ufn_Last24Hrs
(
    @start DateTime2(7)
)
RETURNS @Result TABLE (d char(10), h int)
AS
BEGIN
    DECLARE @current DateTime2(7) = @start

    WHILE (@current > DateAdd(hour, -24, @start))
    BEGIN
        INSERT INTO @Result
        VALUES
        (
            REPLACE(CONVERT(char(10), @current, 102) , '.', '-'),
            DATEPART(hour, @current)
        )

        SET @current = DateAdd(hour, -1, @current)
    END

    RETURN;
END;
GO

SELECT * FROM ufn_Last24Hrs(SYSDATETIME());

SELECT 
    d,h,COUNT(1)cnt 
FROM 
    ufn_Last24Hrs(SYSDATETIME()) hrs
    left join msgs 
        ON msgs.d = hrs.d
        and msgs.h = hrs.h
WHERE dt>= DateAdd(hour, -24, SYSDATETIME()) 
GROUP BY d,h 
ORDER BY 1 DESC, 2 DES

作为替代解决方案,您可以使用此查询来提供所有 24 小时范围。然后简单地将这些值与您的原始查询相加并汇总到 return 只有 24 行。

;WITH hrs AS
(
    SELECT h = 1
    UNION ALL
    SELECT h + 1
    FROM hrs
    WHERE h + 1 <= 24
)
SELECT 
    d = left(convert(varchar(50),DateAdd(hour, -1 * h, getdate()), 21),10), 
    h = DatePart(hour, DateAdd(hour, -1 * h, getdate())), 
    cnt = 0
FROM hrs