【问题标题】:Count consecutive rows for each customer and value计算每个客户和值的连续行
【发布时间】:2021-11-06 12:04:10
【问题描述】:

我有下表:

create table tickets (id int, customer text, status smallint);

insert into tickets values
(1, 'A', 0),
(2, 'A', 0),
(3, 'B', 0),
(4, 'B', 0),
(5, 'A', 0),
(6, 'B', 1),
(7, 'C', 0),
(8, 'B', 0),
(9, 'A', 0),
(10, 'B', 0),
(11, 'A', 1),
(12, 'A', 1),
(13, 'A', 1);

我试图根据这个线程找出我的情况:

Count Number of Consecutive Occurrence of values in Table

但我能做到的最好的就是这个,这还不是我的预期输出

select customer, status, count(*) as cnt
from (select t.*,
             (row_number() over (order by id) -
              row_number() over (partition by customer, status order by id)
             ) as grp
      from tickets t
     ) x
group by grp, customer, status
order by max(id)

DBFiddle

预期输出将是:(每个客户的每个状态的连续记录)

+-----------+-------+-----+
| customer  | status| cnt |
+-----------+-------+-----+
|  A        | 0     |   4 |
|  A        | 1     |   3 |
|  B        | 0     |   2 |
|  B        | 1     |   1 |
|  B        | 0     |   2 |
|  C        | 0     |   1 |

【问题讨论】:

    标签: sql postgresql row-number


    【解决方案1】:

    对于间隙和孤岛解决方案,对于第一个 row_number,您需要按客户分区。

    SELECT customer,    status, COUNT(*) FROM (
    select t.*,
                 (row_number() over (partition by customer order by id) -
                  row_number() over (partition by customer, status order by id)
                 ) as grp
          from tickets t
    ) X
    GROUP BY customer,  status, grp
    ORDER BY customer,  max(id)
    

    dbfiddle

    结果:

    customer    status  count
    --------    ------  -----
    A           0       4
    A           1       3
    B           0       2
    B           1       1
    B           0       2
    C           0       1
    

    【讨论】:

    • 谢谢!像我预期的那样工作
    猜你喜欢
    • 2022-12-15
    • 2021-05-08
    • 2019-03-28
    • 1970-01-01
    • 2012-10-18
    • 2017-08-08
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    相关资源
    最近更新 更多