带有子组件和限制的一对多查询

时间:2013-10-07 19:13:03

标签: mysql one-to-many

要求:从2011年9月到当前日期,选择5个或更多发票总额超过3000美元的客户。

DBMS:MySQL 5.6

表:

  • 客户:customerID(...)
  • invoice:customerID,invoice_no,order_date,order_total(...)

我写了几个MySQL查询。最接近工作的那个出现在下面。结果的问题有两个:

  1. 它会查看每个客户的所有发票总数,而不仅仅是日期范围内的发票。

  2. 它会提取一些(但不是全部)超出日期范围的记录。

  3. 以下是查询:

    #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
    

    非常感谢任何帮助。

    感谢。

1 个答案:

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