0

I have following table:

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);

I was trying to figure out my case basing on this thread:

Count Number of Consecutive Occurrence of values in Table

But best I was able to achieve is this, which is not yet my expected output

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

Expected output would be: (consecutive records with each status for each customer)

+-----------+-------+-----+
| customer  | status| cnt |
+-----------+-------+-----+
|  A        | 0     |   4 |
|  A        | 1     |   3 |
|  B        | 0     |   2 |
|  B        | 1     |   1 |
|  B        | 0     |   2 |
|  C        | 0     |   1 |
sh4rkyy
  • 343
  • 2
  • 19

1 Answers1

1

For gaps and islands solution, for first row_number you need to partition by customer.

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

Result:

customer    status  count
--------    ------  -----
A           0       4
A           1       3
B           0       2
B           1       1
B           0       2
C           0       1
Serkan Arslan
  • 13,158
  • 4
  • 29
  • 44