查询以查找累积,同时减去其他计数

时间:2014-09-21 05:00:46

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

这是我的表结构

Id     INT
RecId  INT
Dated  DATETIME
Status INT

这是我的数据。

状态表(包含不同的状态)

Id   Status
1    Created
2    Assigned

日志表(包含记录经历的不同状态的日志(RecId))

Id   RecId     Dated                              Status  

1     1       2013-12-09 14:16:31.930               1
2     7       2013-12-09 14:27:26.620               1
3     1       2013-12-09 14:27:26.620               2
3     8       2013-12-10 11:14:13.747               1
3     9       2013-12-10 11:14:13.747               1
3     8       2013-12-10 11:14:13.747               2

我需要以下列格式从这些数据生成报告。

Dated                     Created                   Assigned
2013-12-09                 2                         1
2013-12-10                 3                         1

此处行数据按日期计算。 Created计算为(先前记录(日期)创建计数 - 上一个日期指定计数)+今天创建计数。

例如,如果在日期2013-12-10中有三个条目用于记录表,其中两个具有已创建状态,而其中一个已分配状态。因此,在我想要为报告构建的所需视图中,对于日期2013-12-10,视图将返回Created为2 + 1 = 3,其中2是在日志表中新插入的记录,1是前一天剩余记录计数(创建 - 已分配)2 - 1.

我希望情景很明确。如果需要进一步的信息,请询问我。

请帮我用sql构建上面的视图。

1 个答案:

答案 0 :(得分:1)

这与提供的样本的预期结果相匹配,但可能需要更多测试。

with CTE as (
        select
                  *
                , row_number() over(order by dt ASC) as rn
        from (
              select
                      cast(created.dated as date) as dt
                    , count(created.status)       as Created
                    , count(Assigned.status)      as Assigned
                    , count(created.status) 
                      - count(Assigned.status)    as Delta
              from LogTable created
              left join LogTable assigned
                           on created.RecId = assigned.RecId
                          and created.status = 1
                          and assigned.Status = 2
                          and created.Dated <= assigned.Dated
              where created.status = 1
              group by
                      cast(created.dated as date)
          ) x
     )
select
    dt.dt
  , dt.created + coalesce(nxt.delta,0) as created
  , dt.assigned
from CTE dt
left join CTE nxt on dt.rn = nxt.rn+1
;

结果:

|         DT | CREATED | ASSIGNED |
|------------|---------|----------|
| 2013-12-09 |       2 |        1 |
| 2013-12-10 |       3 |        1 |

See this SQLFiddle demo