I have a SQL Server database with a transactions
table with client_id
, date
, and is_cancelled
.
I'm trying to get the client_ids that have 3 or more transactions in a row marked as is_cancelled, along with the in_a_row count. I've gotten as far as the following, which gives me a 1 for is_same when the is_cancelled supports are consecutive, and a running total of cancelled transactions (which is not quite what I need)
SELECT
client_id,
date,
is_same,
SUM(is_same) OVER (PARTITION BY client_id ORDER BY date) AS sum_same,
transCancelled
FROM
(
SELECT
client_id,
LAG(is_cancelled) OVER (PARTITION BY client_id ORDER BY date) AS previous_cancelled,
CASE
WHEN is_cancelled = LAG(is_cancelled) OVER (PARTITION BY client_id ORDER BY date)
THEN 1
ELSE 0
END as is_same,
date,
is_cancelled
FROM transactions
WHERE deleted_at IS NULL -- Ignore soft-deleted rows
) AS t_01
WHERE previous_cancelled = 1
ORDER BY date
Fiddle with sample data: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=a0c9b12203ab2d0c83f73604ccc9d0a0
Expected data (client_id, count)
1, 3
3, 6
CREATE TABLE
INSERT
statements) and expected results would helpsum_same
and filterHAVING COUNT(*) > 3
, you will need to subquery again for this