要求:从2011年9月到当前日期,选择5个或更多发票总额超过3000美元的客户。
DBMS:MySQL 5.6
表:
我写了几个MySQL查询。最接近工作的那个出现在下面。结果的问题有两个:
它会查看每个客户的所有发票总数,而不仅仅是日期范围内的发票。
它会提取一些(但不是全部)超出日期范围的记录。
以下是查询:
#Customers with 5 or more invoices Totaling more than $3000 From Sept 2011 to current
SELECT distinct c2.customerID,c2.firstname,c2.lastname,c2.company,c2.address,c2.address2,c2.city,c2.state,c2.country,c2.phone,c2.email,SUM(c1.order_total)
FROM
customers c2 LEFT JOIN invoice c1
ON c2.customerID = c1.customerID
AND ((date(c1.order_date)) between '2011-09-01' and date(now()))
GROUP BY
c1.customerID
HAVING
COUNT(c1.invoice_no)>=7 and sum(c1.order_total) >=3000
非常感谢任何帮助。
感谢。
答案 0 :(得分:0)
这应该这样做:
select c.*, SUM(i.order_total) total, COUNT(*) order_count
FROM customers c
JOIN invoice i ON c.customerID = i.customerID
WHERE i.order_date >= '2011-09-01'
GROUP BY c.customerID
HAVING order_count >= 5 and total > 3000