[英]SQL How to query customers who have made a purchase at least once a year since they first start purchasing?
您可以使用group by
並having
以下內容:
Select customerid
From t
Group by customerid
Having max(year) - min(year) + 1 = count(distinct year)
and min(purchase) > 10
據推測,您希望每年都達到當前年份。 或者,至少到數據中的最大年份。
select t.customerid
from (select t.*, max(year) over () as max_year
from t
) t
group by customerid, max_year
having max_year - min(year) + 1 = count(distinct year) and
min(purchase) >= 10;
這將禁止在 2017 年和 2018 年購買超過 10 次但在 2019 年或 2020 年沒有數據的客戶。
在 mysql 你可以嘗試:
SELECT * FROM (
SELECT t.CustomerID, COUNT(*) AS yearsPurchasing, t2.firstYear
FROM customers t
JOIN (
SELECT CustomerID, MIN(YEAR) AS firstYear
FROM customers
GROUP BY CustomerID
) t2 ON t2.CustomerID = t.CustomerID
WHERE t.Purchase >= 10
GROUP BY t.CustomerID
) r WHERE 2020 + 1 = firstYear + yearsPurchasing
2020 年是他們應該購買的年份,如果你想要實際年份,你可以使用 YEAR(NOW()) 而不是 2020,如果你想直到最后一年將 2020 + 1 改為 YEAR(NOW()),告訴我如果它有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.