SQL Query to return 24 hour, hourly count even when no values exist?

前端 未结 6 1360
-上瘾入骨i
-上瘾入骨i 2021-01-14 08:53

I\'ve written a query that groups the number of rows per hour, based on a given date range.

SELECT CONVERT(VARCHAR(8),TransactionTime,101) + \' \' + CONVERT(         


        
6条回答
  •  遥遥无期
    2021-01-14 09:23

    So going back to using Remus' original function, I've re-used it in a recursive call and storing the results in a temp table:

    DECLARE @count INT
    DECLARE @NumDays INT
    DECLARE @StartDate DATETIME
    DECLARE @EndDate DATETIME
    DECLARE @CurrentDay DATE
    
        DECLARE @tmp_Transactions TABLE 
        (
            StartHour DATETIME,
            TotalHourlyTransactions INT
        )   
    
    SET @StartDate = '2000/02/10'
    SET @EndDate = '2010/02/13'
    SET @count = 0
    SET @NumDays = DateDiff(Day, @StartDate, @EndDate)
    WHILE @count < @NumDays 
        BEGIN
            SET @CurrentDay = DateAdd(Day, @count, @StartDate)
            INSERT INTO @tmp_Transactions (StartHour, TotalHourlyTransactions)
                SELECT  h.StartHour ,
                        t.TotalHourlyTransactions
                FROM    tvfGetDay24Hours(@CurrentDay) AS h
                        OUTER APPLY ( SELECT    COUNT(TransactionID) AS TotalHourlyTransactions
                                      FROM      [dbo].[TerminalTransactions]
                                      WHERE     TransactionTime BETWEEN h.StartHour AND h.EndHour
                                                AND TerminalId = 4
                                    ) AS t
                ORDER BY h.StartHour
            SET @count = @Count + 1
        END 
    
    SELECT *
    FROM @tmp_Transactions
    

提交回复
热议问题