【发布时间】:2019-05-07 05:33:34
【问题描述】:
我想获取列值的计数,但条件基于其他列值。 例如:在数据下方,第一列为身份,第二列为 statusId,第三列为重复 custId,第四列为 status。
id statusId CustId status
1 1 100 E
2 1 100 E
3 1 100 E
4 2 100 S
5 1 100 E
6 1 100 E
7 2 100 S
8 1 200 E
9 1 200 E
10 2 200 S
11 2 200 S
12 1 200 E
13 2 200 S
我有used Row_Number() 功能,但它没有帮助实现它。
select case when Status = 'S' then 0
when Status = 'E' then sum(case when Status = 'E' then 1 else 0 end) over (order by Id asc) end as cnt
from cust
预期结果:我希望使用选择查询(不是任何循环)获得以下格式的结果。
CusId ExpectedCount
100 2 -- there are two rows with status E before last S
200 1 -- There is one row with status E before last S
为了实现上述结果,我正在计算具有状态 E 的行并将其重置为状态 S 的 0,并且状态 E 的最终计数应在最后一个状态 S 之前返回。
实际结果:我得到状态值“E”的计数并且计数没有被重置,它继续计数。 例如。
custId Id Status ExpectedCount
100 1 E 1
100 2 E 2
100 3 E 3
100 4 S 0
100 5 E 4
100 6 E 5
100 7 E 6
【问题讨论】:
-
你的 dbms 是什么?
-
SQL Server 2014
标签: sql sql-server