选择在日期范围内花费超过特定金额的客户

时间:2016-09-01 14:36:38

标签: mysql sql

我有一个销售表,每个销售交易都有一行。此表还有销售日期和客户ID。

我正在寻找一种方法来选择在指定日期范围内具有指定范围总支出的所有客户。例如,让所有使用between 100 and 1000between 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的客户。

任何人都可以提供帮助。

2 个答案:

答案 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;