SQL +累积计数和总和

时间:2014-12-14 12:18:19

标签: sql sql-server sql-server-2005

我有一个表名为WO,它显示何时请求工作订单(WOPK)以及何时完成。如果完成值的值为null,则表示它尚未完成。

WOPK        Requested  Complete
----------- ---------- ----------
1111        2014-12-11 NULL
2222        2014-12-11 2014-12-11
3333        2014-12-11 2014-12-12
4444        2014-12-12 2014-12-12
5555        2014-12-12 NULL
6666        2014-12-13 NULL

我想计算每个日历日未完成的工作订单的累计数量,从同一天或之前几天开始计算。

期望的结果:

Requested         Count of Not Complete Work Orders (cumulative)
-----------      -----------------------------------------------
2014-12-11             2
2014-12-12             2
2014-12-13             3

请指教。 Ali Nazarian

1 个答案:

答案 0 :(得分:1)

您可以使用相关子查询执行此操作:

select wo.*,
       (select count(*)
        from wo wo2
        where wo2.requested <= wo.requested and
              wo2.complete is null
       ) as RunningNotCompleted
from wo;

这是标准SQL,几乎可以在任何数据库中使用,包括您标记的数据库。

编辑:

如果您只想在白天使用此功能,请使用group by

select requested,
       (select count(*)
        from wo wo2
        where wo2.requested <= wodate.requested and
              wo2.complete is null
       ) as RunningNotCompleted
from (select wo.requested, count(*) as cnt
      from wo
      group by wo.requested
     ) wodate;

我注意到这是标准的SQL,可以在任何数据库中运行。但是,还有其他特定于SQL Server和MySQL的方法。

相关问题