使用group by时的条件计算

时间:2014-04-14 06:09:17

标签: mysql

我有3个表订单,orderitem,发货。我必须得到所有这些和物品的MRP的计数 这是以下查询

    SELECT
  DATE_FORMAT(order.orderdate,"%Y-%m%-%d") AS i_orderdt,
  COUNT(DISTINCT order.orderid) AS i_orderscount,
  COUNT(DISTINCT orderitem.orderitemid) as i_orderitemcount,
  COUNT(DISTINCT shipment.shipmentid) AS i_shipmentcount,
  ROUND(SUM(ifnull(orderitem.unitprice,0) * orderitem.quantity),0) AS i_mrp,
FROM order
    LEFT JOIN shipment
        ON shipment.orderid = order.orderid 
    JOIN orderitem
        ON orderitem.orderid = order.orderid

    WHERE order.orderdate >= "2014-01-01 00:00:00" AND order.orderdate <= "2014-03-31 23:59:59" )  GROUP BY DATE_FORMAT(`order`.`orderdate`,"%y-%m%-%d")

但MRP出错了,因为发货的订单将是1对多的关系。我如何编写查询,以便计算仅针对不同的orderitemid ??

进行

1 个答案:

答案 0 :(得分:0)

一种解决方案是将装运计数移动到子查询中:

SELECT
  DATE_FORMAT(order.orderdate,"%Y-%m%-%d") AS i_orderdt,
  COUNT(DISTINCT order.orderid) AS i_orderscount,
  COUNT(DISTINCT orderitem.orderitemid) as i_orderitemcount,
  COALESCE(
  (
    SELECT COUNT(DISTINCT shipmentid) 
    FROM shipment 
    WHERE shipment.orderid = order.orderid 
  ), 0) AS i_shipmentcount,
  ROUND(SUM(ifnull(orderitem.unitprice,0) * orderitem.quantity),0) AS i_mrp,
FROM order
JOIN orderitem ON orderitem.orderid = order.orderid
WHERE order.orderdate >= "2014-01-01 00:00:00" 
AND order.orderdate <= "2014-03-31 23:59:59" ) 
GROUP BY DATE_FORMAT(order.orderdate,"%y-%m%-%d");