Esto seleccionará a todos los clientes con al menos dos acciones consecutivas del mismo tipo.
WITH rows AS
(
SELECT customer, action,
ROW_NUMBER() OVER (PARTITION BY customer ORDER BY lastlogin) AS rn
FROM mytable
)
SELECT DISTINCT customer
FROM rows rp
WHERE EXISTS
(
SELECT NULL
FROM rows rl
WHERE rl.customer = rp.customer
AND rl.rn = rp.rn + 1
AND rl.action = rp.action
)
Esta es la consulta más eficiente solo para la acción 2
:
WITH rows AS
(
SELECT customer, ROW_NUMBER() OVER (PARTITION BY customer ORDER BY lastlogin) AS rn
FROM mytable
WHERE action = 2
)
SELECT DISTINCT customer
FROM rows rp
WHERE EXISTS
(
SELECT NULL
FROM rows rl
WHERE rl.customer = rp.customer
AND rl.rn = rp.rn + 1
)
Actualización 2:
Para seleccionar rangos ininterrumpidos:
WITH rows AS
(
SELECT customer, action, lastlogin
ROW_NUMBER() OVER (PARTITION BY customer ORDER BY lastlogin) AS rn
ROW_NUMBER() OVER (PARTITION BY customer, action ORDER BY lastlogin) AS series
FROM mytable
)
SELECT DISTINCT customer
FROM (
SELECT customer
FROM rows rp
WHERE action
GROUP BY
customer, actioncode, series - rn
HAVING
DETEDIFF(day, MIN(lastlogin), MAX(lastlogin)) >= 14
) q
Esta consulta calcula dos series:una devuelve ORDER BY lastlogin
contiguos , el segundo particiona por action
adicionalmente:
action logindate rn series diff = rn - series
1 Jan 01 1 1 0
1 Jan 02 2 2 0
2 Jan 03 3 1 2
2 Jan 04 4 2 2
1 Jan 05 5 3 2
1 Jan 06 6 4 2
Mientras la diferencia entre los dos esquemas sea la misma, las series son ininterrumpidas. Cada interrupción rompe la serie.
Esto significa que la combinación de (action, diff
) define los grupos ininterrumpidos.
Podemos agrupar por action, diff
, busca MAX
y MIN
dentro de los grupos y filtrarlos.
Si necesita seleccionar 14
filas en lugar de 14
días consecutivos, solo filtre en COUNT(*)
en lugar de DATEDIFF
.