SQL SERVER COUNT LEAD条件组BY

时间:2017-04-19 11:29:14

标签: sql sql-server count group-by grouping

我试图找到一种基于组计数的方法,但我无法找到一种方法而不必使用Cursor。由于使用Cursor相对较慢,我希望可能有更好的方法。

简化数据的结构如下:

    +----+--------+-------+--------+
    | ID | NEXTID | RowNo | Status |
    +----+--------+-------+--------+
    |  1 |      2 |   1   |      1 |
    |  2 |      3 |   1   |      1 |
    |  3 |      4 |   1   |      0 |
    |  4 |        |   1   |      1 |
    |  1 |      2 |   2   |      0 |
    |  2 |      3 |   2   |      1 |
    |  3 |      4 |   2   |      1 |
    |  4 |        |   2   |      1 |
    |  1 |      2 |   3   |      1 |
    |  2 |      3 |   3   |      1 |
    |  3 |      4 |   3   |      1 |
    |  4 |        |   3   |      1 |
    +----+--------+-------+--------+

我现在想要在组中计算Status列,结果是:

    +-----+-------------+
    | Row | StatusCount |
    +-----+-------------+
    |   1 |           2 |
    |   1 |           1 |
    |   2 |           3 |
    |   3 |           4 |
    +-----+-------------+

出于测试目的,我创建了以下代码:

    SELECT
        ID,
        NEXTID,
        RowNo,
        Status,
        LEAD(ID,1,0)
            OVER (ORDER BY RowNo,ID) AS LEADER
    INTO #TestTable
    FROM 
    (
        VALUES
            (1, 2,  1,  1),
            (2, 3,  1,  1),
            (3, 4,  1,  0),
            (4, '', 1,  1),
            (1, 2,  2,  0),
            (2, 3,  2,  1),
            (3, 4,  2,  1),
            (4, '', 2,  1),
            (1, 2,  3,  1),
            (2, 3,  3,  1),
            (3, 4,  3,  1),
            (4, '',  3, 1)

    )
    AS TestTable(
        ID,
        NEXTID,
        RowNo,
        Status);
    GO

    SELECT
        RowNo,
        Count(Status) AS StatusCount
    FROM #TestTable
    WHERE
        Status = 1
    GROUP BY
        RowNo

这导致

     +-----+-------------+
     | Row | StatusCount |
     +-----+-------------+
     |   1 |           3 |
     |   2 |           3 |
     |   3 |           4 |
     +-----+-------------+

不分隔第一行。我确实意识到我需要另一个GROUP BY条件,但我无法找出合适的条件。

非常感谢你的帮助。如果已经回答这个问题,我无法找到主题,也会对提示表示赞赏。

亲切的问候 freubau

1 个答案:

答案 0 :(得分:0)

您可以通过对每个数字执行零的累积和来识别组。然后,其余的只是聚合:

select rowno, count(*)
from (select t.*,
             sum(case when status = 0 then 1 else 0 end) over (partition by rowno order by id) as grp
      from #TestTable t
     ) t
where status = 1
group by rowno, grp
order by rowno, grp;

Here是一个rex测试者。