当列匹配值时,有效的ROW_NUMBER增量

时间:2018-06-01 11:35:50

标签: sql tsql sql-server-2012

我正在尝试找到一种有效的方法,仅从ExpectedId派生下面的列State。我想要的是,每次ExpectedState时,0的数量会增加Id(按+----+-------+----------+ | Id | State | Expected | +----+-------+----------+ | 1 | 0 | 1 | | 2 | 1 | 1 | | 3 | 0 | 2 | | 4 | 1 | 2 | | 5 | 4 | 2 | | 6 | 2 | 2 | | 7 | 3 | 2 | | 8 | 0 | 3 | | 9 | 5 | 3 | | 10 | 3 | 3 | | 11 | 1 | 3 | +----+-------+----------+ 排序)。

WITH Groups AS 
(
   SELECT Id, ROW_NUMBER() OVER (ORDER BY Id) AS GroupId FROM tblState WHERE State=0
)
SELECT S.Id, S.[State], S.Expected, G.GroupId FROM tblState S
   OUTER APPLY (SELECT TOP 1 GroupId FROM Groups WHERE Groups.Id <= S.Id ORDER BY Id DESC) G

我已经设法通过以下SQL实现了这一点,但是当数据集很大时执行时间很短:

vis_util

是否有更简单,更有效的方法来产生这种结果? (在SQL Server 2012或更高版本中)

2 个答案:

答案 0 :(得分:5)

只需使用累计金额:

select s.*,
       sum(case when state = 0 then 1 else 0 end) over (order by id) as expected
from tblState s;

答案 1 :(得分:0)

其他方法使用subquery

select *,
       (select count(*)
        from table t1
        where t1.id < t.id and state = 0
       ) as expected
from table t;