一个SQL语句中的多个计算值

时间:2013-07-04 07:17:46

标签: sql datediff

我正在尝试完成一个程序的问题。我有一个存储三个时间戳的表。它用于统计查询和响应。第一个时间戳是查询的日期和时间(Date_Sent),另外两个是我们的专家之一第一次响应查询(FirstResponse)以及何时满足该查询(LastResponse)。我应该根据以下标准创建一个图表:

  1. 每月查询总数
  2. 在不到两小时内回复的查询数
  3. 查询数量在不到24小时但超过两个
  4. 时响应
  5. 在不到48小时但超过24小时内回复的查询数量
  6. 查询次数少于72小时但超过48
  7. 查询次数少于96小时但超过72
  8. 我能够做到第一个要求:

    SELECT Count(Date_Sent) AS TotalQueries, 
           SUBSTRING(CONVERT(VARCHAR(11), Date_Sent, 113), 4, 8) AS Month, 
           RIGHT(CONVERT(VARCHAR(7), Date_Sent, 120), 2) AS Month_Order 
    FROM AskAO.dbo.AskAO_Stats 
    WHERE Date_Sent BETWEEN '6/1/2012' AND '6/30/2013' AND 
          FirstResponse != '' AND 
          LastResponse != '' AND 
          FirstResponse < LastResponse   
    GROUP BY SUBSTRING(CONVERT(VARCHAR(11), Date_Sent, 113), 4, 8), 
             CONVERT(VARCHAR(7), Date_Sent, 120) 
    ORDER BY SUBSTRING(CONVERT(VARCHAR(11), Date_Sent, 113), 4, 8)
    

    我能够得到这个样本结果:

    TotalQueries     Month   Month_Order
        655        Jun 2013      06
        289        May 2013      05
    

    然而,我不知道如何获得其他人:(我知道我可以通过DateDiff计算价值,但我需要的是每月满足这些特定标准的查询数量。我需要这个:

     TotalQueries   2Hrs  24Hrs  48Hrs  72Hrs  96Hrs  Month     Month_Order
         655        300    190    80     55     30    Jun 2013      06
         289        180     50    30     15     14    May 2013      05
    

    我不熟悉复杂的SQL,所以我不确定这是否可行。

2 个答案:

答案 0 :(得分:3)

尝试这样的事情

SELECT Count(Date_Sent) AS TotalQueries, 
    SUBSTRING(CONVERT(VARCHAR(11), Date_Sent, 113), 4, 8) AS Month, 
    RIGHT(CONVERT(VARCHAR(7), Date_Sent, 120), 2) AS Month_Order ,
    SUM(CASE WHEN DATEDIFF(HOUR, FirstResponse, LastResponse) < 2 THEN 1 ELSE 0 END) AS LessThan2Hours,
    SUM(CASE WHEN DATEDIFF(HOUR, FirstResponse, LastResponse) between 2 AND 24 THEN 1 ELSE 0 END) AS LessThan24Hours,
    SUM(CASE WHEN DATEDIFF(HOUR, FirstResponse, LastResponse) between 25 AND 48 THEN 1 ELSE 0 END) AS LessThan24Hours,
    SUM(CASE WHEN DATEDIFF(HOUR, FirstResponse, LastResponse) between 25 AND 48 THEN 1 ELSE 0 END) AS LessThan48Hours,
    SUM(CASE WHEN DATEDIFF(HOUR, FirstResponse, LastResponse) between 49 AND 72 THEN 1 ELSE 0 END) AS LessThan72Hours,
    SUM(CASE WHEN DATEDIFF(HOUR, FirstResponse, LastResponse) between 73 AND 96 THEN 1 ELSE 0 END) AS LessThan96Hours

FROM AskAO.dbo.AskAO_Stats 
WHERE Date_Sent BETWEEN '6/1/2012' AND '6/30/2013' AND FirstResponse != '' AND LastResponse != '' AND FirstResponse < LastResponse   
GROUP BY SUBSTRING(CONVERT(VARCHAR(11), Date_Sent, 113), 4, 8), CONVERT(VARCHAR(7), Date_Sent, 120) 
ORDER BY SUBSTRING(CONVERT(VARCHAR(11), Date_Sent, 113), 4, 8)

答案 1 :(得分:1)

COUNT()仅计算非空值。因此,您可以根据您的逻辑以某种方式在COUNT(...)内编写一些表达式,当您不想总结该行时它等于null,否则不为null。例如,要在不到两小时内计算答案数量,您可以写下:

COUNT(CASE WHEN DATEDIFF(HOUR, Date_Sent, FirstResponse) < 2 THEN Date_Sent ELSE NULL END) AS [2Hrs]

你可以做所有其他相似的案件。