我有一个销售表,每个销售交易都有一行。此表还有销售日期和客户ID。
我正在寻找一种方法来选择在指定日期范围内具有指定范围总支出的所有客户。例如,让所有使用between 100 and 1000
,between 2016-07-01 and 2016-08-15
的客户获得。然后,这必须成为更大查询的一部分。
此查询
select
customer_id,
sum(sale_amount)
from
sales_receipt
where
DATE(sales_receipt.sale_date) BETWEEN '2016-07-01' AND '2016-08-29'
group by
customer_id;
告诉我所有客户及其在指定日期范围内的总支出,但我只需要sum(sale_amount)
为between 100 and 1000
的客户。
任何人都可以提供帮助。
答案 0 :(得分:2)
尝试使用
select customer_id, sum(sale_amount) from sales_receipt where
DATE(sales_receipt.sale_date) BETWEEN '2016-07-01' AND '2016-08-29'
group by customer_id having sum(sale_amount)>=100 and sum(sale_amount)<=100
答案 1 :(得分:1)
您在此处使用HAVING
子句,因为您想要filter on the aggregated result:
SELECT
customer_id,
SUM(sale_amount) AS total_amount
FROM sales_receipt
WHERE DATE(sales_receipt.sale_date) BETWEEN '2016-07-01' AND '2016-08-29'
HAVING total_amount BETWEEN 100 AND 1000
GROUP BY customer_id;