Dette er lidt vanskeligt, og for at finde resultater, der er støt stigende eller faldende, vil du sandsynligvis bruge MATCH_RECOGNIZE
klausul, som MySQL (endnu) ikke understøtter. På denne måde kan du definere et mønster, hvor hvert antal er mindre end den foregående værdi. Derudover kunne du sikkert gøre dette med en rekursiv cte, men det ville være uden for mine evner.
Her er, hvad jeg fandt på, med det forbehold, at det kun sammenligner den første og sidste værdi:
WITH
tbl (customer, purchasedate, quantity) AS (
SELECT * FROM VALUES
('Bob', '9/1/2021', 10),
('Bob', '9/10/2021', 6),
('Bob', '9/18/2021', 5),
('Bob', '9/19/2021', 8),
('Mary', '9/1/2021', 10),
('Mary', '9/10/2021', 6),
('Mary', '9/18/2021', 5),
('Mary', '9/19/2021', 3),
('Frank', '9/1/2021', 5),
('Lucus', '9/1/2021', 5),
('Lucus', '9/10/2021', 6),
('Lucus', '9/18/2021', 10)
)
SELECT
DISTINCT customer
FROM
tbl
QUALIFY
FIRST_VALUE(quantity) OVER (partition BY customer ORDER BY purchasedate)
> LAST_VALUE(quantity) OVER (PARTITION BY customer ORDER BY purchasedate)
Hvilket giver:
CUSTOMER
Bob
Mary
Eller, for at få strengt faldende med et kendt maksimum, kan du kæde dem alle sammen, hvilket bliver ret grimt:
WITH
tbl (customer, purchasedate, quantity) AS (
SELECT * FROM VALUES
('Bob', '9/1/2021', 10),
('Bob', '9/10/2021', 6),
('Bob', '9/18/2021', 5),
('Bob', '9/19/2021', 8),
('Mary', '9/1/2021', 10),
('Mary', '9/10/2021', 6),
('Mary', '9/18/2021', 5),
('Mary', '9/19/2021', 3),
('Frank', '9/1/2021', 5),
('Lucus', '9/1/2021', 5),
('Lucus', '9/10/2021', 6),
('Lucus', '9/18/2021', 10)
)
SELECT
DISTINCT customer
FROM
tbl
qualify
(NTH_VALUE(quantity, 1) OVER (partition BY customer ORDER BY purchasedate) >= NTH_VALUE(quantity, 2) OVER (partition BY customer ORDER BY purchasedate))
and ((NTH_VALUE(quantity, 2) OVER (partition BY customer ORDER BY purchasedate) >= NTH_VALUE(quantity, 3) OVER (partition BY customer ORDER BY purchasedate)) or (NTH_VALUE(quantity, 3) OVER (partition BY customer ORDER BY purchasedate) is null))
and ((NTH_VALUE(quantity,3) OVER (partition BY customer ORDER BY purchasedate) >= NTH_VALUE(quantity, 4) OVER (partition BY customer ORDER BY purchasedate)) or (NTH_VALUE(quantity, 4) OVER (partition BY customer ORDER BY purchasedate) is null))
Hvilket giver:
CUSTOMER
Mary
Selvom jeg for et ukendt beløb ville tro match_recognize
ville være den bedste løsning (eller du kan tilføje noget rekursion eller en brugerdefineret funktion).