WITH addColumn AS ( select rank() OVER (ORDER BY [m-pay_sub_ops_date] ) as rank, *
From [m-pay_subscriber_operations]
),
partitioned AS (
SELECT
*,
rank - ROW_NUMBER() OVER (order by rank) AS grp
FROM addColumn
WHERE [m-pay_sub_ops_result_code] = '73' and [m-pay_sub_ops_msisdn_pioneer] = '22103248'
),
counted AS (
SELECT
*,
COUNT(*) OVER (PARTITION BY grp) AS cnt
FROM partitioned
),
ranked AS (SELECT
*,
RANK() OVER (ORDER BY [m-pay_sub_ops_date] desc, grp) AS rnk
FROM counted where cnt >5
)
SELECT
[m-pay_sub_ops_date] , [m-pay_sub_ops_msisdn_pioneer], [m-pay_sub_ops_result_code], grp, cnt
FROM ranked
WHERE rnk = 1
;