SQL用于计算在给定时间打开的任务数

时间:2014-03-24 10:47:49

标签: sql sql-server sql-server-2008 tsql

我有一个很好的查询,可以计算在给定的一周内打开和关闭了多少任务,但是我在扩展它时遇到了困难,因此我可以向我展示我们有多少任务。那个星期结束时仍然开放。

在我看来,sql需要计算从一开始就打开的问题总数,直到那个星期,然后对关闭的数量做同样的事情并相互减去两个但是由于我对SQL的了解有限,我正在努力解决这个问题,因为它不属于group by子句。

这是我的SQL:

SELECT  ISNULL(A.[Year],B.[Year]) [Year],
        ISNULL(A.[Week],B.[Week]) [Week],
        ISNULL(A.Opened,0) Opened,
        ISNULL(B.Closed,0) Closed,
A.totResponse, A.totCompletion
FROM (  SELECT  YEAR(insert_time) [Year],
                DATEPART(WEEK,insert_time) [Week],
                COUNT(id) Opened, sum(timer2) totResponse, sum(timer3) AS totCompletion
        FROM service_req
        WHERE [insert_time] IS NOT NULL and sr_type=1
        GROUP BY YEAR(insert_time), DATEPART(WEEK,insert_time)) A
FULL JOIN ( SELECT  YEAR(close_time) [Year],
                    DATEPART(WEEK,close_time) [Week],
                    COUNT(id) Closed
            FROM service_req 
            WHERE [close_time] IS NOT NULL and sr_type=1
            GROUP BY YEAR(close_time), DATEPART(WEEK,close_time)) B
    ON A.[Year] = B.[Year] AND A.[Week] = B.[Week]
ORDER BY [Year], [Week]

如果有任何人可以帮助我解决这个问题,那将非常感激。

1 个答案:

答案 0 :(得分:0)

真正使这个查询更容易的是累积总和,这是在SQL Server 2012中引入的。在这种情况下,您可以使用row_number()来模拟它,因为您需要累积计数。

因此,我们的想法是计算打开和关闭的累计数量,然后进行聚合。累积数字的max()将是本周末的数字。考虑到这一点,我使用union all而不是full outer join重写了查询:

with oc as (
      SELECT cast(insert_time as date) as thedate, 1 as opened, NULL as closed,
             timer2 as Response, timer3 as Completion,
             row_number() over (order by insert_time) as cumopened, NULL as cumclosed
      FROM service_req
      WHERE insert_time IS NOT NULL and sr_type = 1
      union all
      SELECT cast(close_time as date), NULL as opened, 1 as closed,
             NULL as Response, NULL as Completion,
             NULL as cumopened, row_number() over (order by close_time) as cumclosed
      FROM service_req
      WHERE close_time IS NOT NULL and sr_type = 1
     )
select year(thedate) as [Year],
       datepart(week, thedate) as [Week],
       coalesce(sum(opened), 0) as Opened, coalesce(sum(closed), 0) as closed,
       max(Response) as Response, max(Completion) as completion,
       coalesce(max(cumopened), 0) - coalesce(max(cumclosed), 0) as stillopened
from oc
group by year(thedate), datepart(week, thedate)
order by year(thedate), datepart(week, thedate);

您实际上可以使用相同的想法重写您的查询,只需使用子查询来计算累积数字。

相关问题