【问题标题】:How to get count based on column value that reset it in sql query如何根据在 sql 查询中重置它的列值获取计数
【发布时间】: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


【解决方案1】:

这回答了问题的原始版本。

您可以使用累积和来定义组,然后使用row_number()

select custid, id, status,
       (case when status = 'S' then 0
             else row_number() over (partition by custid, grp, status order by id)
        end) as expectedcount
from (select t.*,
             sum(case when status = 'S' then 1 else 0 end) over (partition by custid order by id) as grp
      from t
     ) t;

Here 是一个 dbfiddle。

【讨论】:

  • 在执行查询 100 后仍然为状态“E”数据 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 给出错误计数1 E 1 100 2 E 2 100 3 E 3 100 5 E 4 100 6 E 5 100 7 S 0 100 4 S 0
  • 我需要将 2 作为最后一行状态作为 S 并且在两行具有状态 E 之前
  • @SachinMalviya,很难理解您对 Gordon 的第一条评论。您可能想要编辑您的问题并添加您的新期望。与此同时,我刚刚针对您在原始问题中的数据运行了 Gordon 的答案,它满足了您列出的两个期望的输出。
  • 我已将我的问题和期望编辑为更易于理解。
  • @SachinMalviya 。 . .如果您更改问题,那么您将不会得到任何有效的答案。
猜你喜欢
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 2018-07-20
  • 1970-01-01
  • 1970-01-01
  • 2019-07-05
  • 1970-01-01
相关资源
最近更新 更多