2

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

  1. 每月查询总数
  2. 在不到两小时内回复的查询数量
  3. 在不到 24 小时但超过两个小时内回复的查询数量
  4. 在不到 48 小时但超过 24 小时内回复的查询数量
  5. 在不到 72 小时但超过 48 小时内回复的查询数量
  6. 在不到 96 小时但超过 72 小时内回复的查询数量

我能够做到第一个要求:

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,所以我不确定这是否可行。

4

2 回答 2

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)
于 2013-07-04T07:32:59.073 回答
1

关键是COUNT()只计算不为空的值。因此,您可以COUNT(...)根据您的逻辑以某种方式在其中编写一些表达式,当您不想对行求和时它等于 null ,否则不等于 null 。例如,要计算不到两个小时内的响应数,您可以编写:

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

您可以对所有其他情况进行类似处理。

于 2013-07-04T07:37:01.940 回答