我的表有4列:branch_name,customer_id,order_value,purchase_date。
"london-branch", 422, "12","01-01-2019"
"manchester", 133, "33","01-04-2019"
"london", 422, "55","01-04-2019"
"newyork", 1223, "11","01-04-2019"
想要找出2019年花了超过2018年总花销额10%以上的顾客。
我尝试过
CREATE TABLE AS LastYr
Select customer_id,order_value from order_table where purchase_date between '01-01-2018' AND '31-12-2018';
这将为2018年创建表格
然后
CREATE TABLE AS NewYear
Select customer_id,order_value from order_table where purchase_date between '01-01-2019' AND '31-12-2019';
然后努力拼凑桌子,找到不同之处。
答案 0 :(得分:1)
您可以在SUM
子句中使用聚合和条件HAVING
:
SELECT customer_id
FROM mytable
WHERE YEAR(purchase_date) IN (2018, 2019)
GROUP BY customer_id
HAVING
SUM(CASE WHEN YEAR(purchase_date) = 2019 THEN order_value ELSE 0 END)
> 1.1 * SUM(CASE WHEN YEAR(purchase_date) = 2018 THEN order_value ELSE 0 END)
注意:这假设您使用相关数据类型而不是字符串存储日期。