MySQL选择使用行计数和分组

时间:2014-01-22 07:27:05

标签: mysql sql group-by sum having-clause

我有2个表,订单和order_lineitems。 订单包含订单状态信息(销售日期,发票号,销售类型等) order_lineitems包含一对多关系中每个订单的项目。 由于我们按行项目提供送货信息,因此ship_date位于order_lineitems表中,如果未发货,则为null,如果发货,则为日期。

我试图通过比较订单项行数与有发货日期的订单项行来提取所有商品已发货的订单。虽然我已成功提取所有信息,但我无法完成最后一步,将结果集限制为仅包含完整发货的订单(行数= ship_date不为空的行数)。

我知道我错过了一些简单的东西,但只是看不到它。

select sum(custom.lineitems) as totalitems, sum(custom.shipped) as totalshipped,
custom.invoice, z.shipregion
from (
 select a.invoice, count(a.invoice) as lineitems, 0 as shipped
 from order_lineitem a
 group by a.invoice

UNION ALL

 select b.invoice, 0 as notshipped, count(b.ship_date) as shipped
 from order_lineitem b
 where b.ship_date is not null
 group by b.invoice
) as custom

left join orders z on custom.invoice = z.invoice
where z.result = 0
and z.respmsg like 'Approved%'
and z.shipregion <> 'PENDING'
and z.cancelorder = 0
group by custom.invoice;

这将返回如此结果集(数据库中每张发票一行)

   totalitems   totalshipped    invoice shipregion
  4           2     1000    REGION08
  1           1     10001   REGION07
  1           1     10004   REGION05
  3           1     10006   REGION05
  2           2     10007   REGION04
  1           1     10008   REGION08    
  7           7     10009   REGION01    
  1           1     1001    REGION08

我正在寻找的是这样的结果集 - 只有在totalitems = totalshipped

的情况下
totalitems  totalshipped    invoice shipregion
  1           1     10001   REGION07
  1           1     10004   REGION05
  2           2     10007   REGION04
  1           1     10008   REGION08    
  7           7     10009   REGION01    
  1           1     1001    REGION08

2 个答案:

答案 0 :(得分:1)

使用HAVING子句

SELECT a.invoice, z.shipregion, COUNT(a.invoice) AS lineitems, 
       SUM(CASE WHEN a.ship_date IS NOT NULL THEN 1 ELSE 0 END) AS shipped
FROM order_lineitem a
LEFT JOIN orders z ON a.invoice = z.invoice AND z.result = 0 AND z.cancelorder = 0 AND 
                      z.respmsg LIKE 'Approved%' AND z.shipregion <> 'PENDING'                         
GROUP BY a.invoice HAVING lineitems = shipped

SELECT a.invoice, a.shipregion, a.lineitems, a.shipped 
FROM (SELECT a.invoice, z.shipregion, COUNT(a.invoice) AS lineitems, 
             SUM(CASE WHEN a.ship_date IS NOT NULL THEN 1 ELSE 0 END) AS shipped
      FROM order_lineitem a
      LEFT JOIN orders z ON a.invoice = z.invoice AND z.result = 0 AND z.cancelorder = 0 AND 
                            z.respmsg LIKE 'Approved%' AND z.shipregion <> 'PENDING'                         
      GROUP BY a.invoice
    ) AS a WHERE a.lineitems = a.shipped

答案 1 :(得分:0)

需要另外一个外部查询。

select * from 
(
    \\Your whole query here
) as Result
where Result.totalitems  = Result.totalshipped