计算过去8小时的每小时交易次数

时间:2014-06-30 08:48:34

标签: sql sql-server sql-server-2005

这是我提出的问题的延伸和早期问题。根据我客户的新要求,我需要在过去的8小时内按小时检索交易次数。

例如:我在2014年6月27日上午5:30登录,我应该能够看到我登录前8小时发生的交易次数,但是按小时分组。

像这样。

27/06/2014 04-05 Hours 2 Transactions
27/06/2014 03-04 Hours 1 Transactions
27/06/2014 02-03 Hours 3 Transactions
27/06/2014 01-02 Hours 4 Transactions
27/06/2014 00-01 Hours 0 Transactions
26/06/2014 23-00 Hours 0 Transactions
26/06/2014 22-23 Hours 1 Transactions
26/06/2014 21-22 Hours 1 Transactions
26/06/2014 20-21 Hours 3 Transactions

我目前使用的SQL脚本基于日常工作,例如

 27/06/2014 04-05 Hours 2 Transactions
 27/06/2014 03-04 Hours 1 Transactions
 27/06/2014 02-03 Hours 3 Transactions
 27/06/2014 01-02 Hours 4 Transactions
 27/06/2014 00-01 Hours 0 Transactions

但这不是我想要的,任何人都可以建议如何修改我的脚本。请

 SELECT 
     DATEADD(day, datediff(day, 0, DateTimeStart), 0) AS ForDate,
     DATEPART(hour, DateTimeStart) AS OnHour, 
     TTID.TTID, COUNT(Trxn.TTID) AS 'TrxnCount'
 FROM 
     TTID 
 LEFT JOIN 
     Trxn ON TTID.TTID = (rtrim(Trxn.TTID) + ltrim(Trxn.STV)) 
          AND Trxn.Status = 'ok' 
 WHERE 
     TTID.Status = 'A' 
     AND DateTimeStart = '2014-06-27' 
 GROUP BY 
     DATEADD(day, datediff(day, 0, DateTimeStart), 0),
     DATEPART(hour, DateTimeStart), TTID.TTID
 ORDER BY 
     DATEADD(day, datediff(day, 0, DateTimeStart), 0) DESC

1 个答案:

答案 0 :(得分:0)

DECLARE @LastHour AS datetime;
SET @LastHour = DATEADD(hour, DATEDIFF(hour, 0, GETDATE()), 0);

WITH HourOffsets AS (
            SELECT -1 AS Offset
  UNION ALL SELECT -2
  UNION ALL SELECT -3
  UNION ALL SELECT -4
  UNION ALL SELECT -5
  UNION ALL SELECT -6
  UNION ALL SELECT -7
  UNION ALL SELECT -8
)
,Periods AS (
    SELECT DATEADD(hour, Offset, @LastHour) AS PeriodStartTime
          ,DATEADD(hour, Offset + 1, @LastHour) AS PeriodEndTime
    FROM HourOffsets
)
,Transactions AS (
    SELECT Periods.PeriodStartTime
          ,COUNT(*) AS TransactionCount
    FROM Periods
         LEFT JOIN TTID
             ON TTID.DateTimeStart >= Periods.PeriodStartTime
                AND TTID.DateTimeStart < Periods.PeriodEndTime
         LEFT JOIN Trxn
             ON TTID.TTID = (rtrim(Trxn.TTID)+ltrim(Trxn.STV))
             AND Trxn.Status='ok'
    WHERE TTID.Status IS NULL
          OR TTID.Status = 'A'
    GROUP BY Periods.PeriodStartTime
)
SELECT CONVERT(varchar(10), PeriodStartTime, 103)
      ,CONVERT(varchar(2), DATEPART(hour, Periods.PeriodStartTime)) + '-'
       CONVERT(varchar(2), DATEPART(hour, Periods.PeriodEndTime))
      ,TransactionCount
FROM Transactions