SQL group by current timestamp

时间:2013-10-09 09:36:47

标签: sql sql-server

我在数据库中有服务请求。我需要知道它们中有多少是按天分组打开/关闭过去2周。

我有这个问题:

SELECT RIGHT('00'+CONVERT(VARCHAR(2), DATEPART(MONTH, OPENTIME)), 2) 
       + '-' 
       + RIGHT('00'+CONVERT(VARCHAR(2), DATEPART(DAY, OPENTIME)), 2) AS 'Day', 
       COUNT(OPENTIME)                                               AS 
       'Count of Opened', 
       COUNT(CLOSETIME)                                              AS 
       'Count of Closed' 
FROM   JEZD.F_SERVICE_REQUESTS 
WHERE  OPENTIME >= DATEADD(DAY, DATEDIFF(DAY, 0, 
                                DATEADD(D, -14, CURRENT_TIMESTAMP)), 0 
                   ) 
GROUP  BY RIGHT('00'+CONVERT(VARCHAR(2), DATEPART(MONTH, OPENTIME)), 2) 
          + '-' 
          + RIGHT('00'+CONVERT(VARCHAR(2), DATEPART(DAY, OPENTIME)), 2) 

这是按OpenTime分组的,例如今天没有服务请求打开,这个SQL不会计算任何已关闭的门票,直到打开一些新的。我曾尝试将where子句和group子句从OpenTime修改为Current_Time,但我收到错误Each GROUP BY expression must contain at least one column that is not an outer reference.您有解决方法吗?

截至目前的数据集:

Day     Opened Closed
09-30   29   21
10-02   23   18
09-27   27   25
10-03   16   12
10-01   59   44
09-26   23   18
10-04   31   20
09-25   35   29
10-07   22   12

1 个答案:

答案 0 :(得分:0)

我会表演:

  1. 查询过去14天内已打开的请求
  2. 查询过去14天内的已结算请求
  3. 完全加入两个日期