我有一个查询
SELECT MONTHNAME(o.sale_on),
SUM(od.current_status_id=1) AS Sales,
SUM(od.current_status_id=2) AS Refunds,
SUM(od.current_status_id=3) AS `Partially Refunded`,
SUM(od.current_status_id=4) AS `Pending`,
SUM(od.price-IFNULL(od.discount,0)+IFNULL(od.additional_charges,0)) AS net_revenue,
SUM(CASE WHEN od.current_status_id=1 THEN od.price-IFNULL(od.discount,0)+IFNULL(od.additional_charges,0) END) AS gross_revenue
FROM orders o
RIGHT JOIN order_detail od USING (order_id)
where 1=1
and year(o.sale_on) = 2015
GROUP BY DATE_FORMAT(o.sale_on,'%Y-%m')
ORDER BY o.sale_on
返回这样的数据
MONTHNAME(o.sale_on) | Sales | Refunds | PartiallyRefunded | Pending | net_revenue | gross_revenue
January | 67 | 0 |0 | 0 | 5971.1600 | 5971.1600
February | 1644 | 1 |0 | 0 | 152.7200 |152.7200
March | 39 | 0 |0 |0 |0.0000 | 0.0000
我想在几个月内展示它,我该怎么做?
我尝试了另一个与master_months表进行连接的查询
SELECT MONTHNAME(o.sale_on),
mo.month_name,
SUM(od.current_status_id=1) AS Sales,
SUM(od.current_status_id=2) AS Refunds,
SUM(od.current_status_id=3) AS `Partially Refunded`,
SUM(od.current_status_id=4) AS `Pending`,
SUM(od.priceIFNULL(od.discount,0)+IFNULL(od.additional_charges,0)) AS net_revenue,
SUM(CASE WHEN od.current_status_id=1 THEN od.price-IFNULL(od.discount,0)+IFNULL(od.additional_charges,0) END) AS gross_revenue
FROM master_months mo
LEFT JOIN orders o ON mo.month_name = MONTHNAME(o.sale_on)
RIGHT JOIN order_detail od USING (order_id)
WHERE 1=1
AND YEAR(o.sale_on) = 2015
GROUP BY DATE_FORMAT(o.sale_on,'%Y-%m')
ORDER BY o.sale_on
但这不起作用。
答案 0 :(得分:1)
在查询中混合left join
和right join
只是令人困惑。您需要一个left join
链,从包含所有月份的表开始。其余所有联接应为left join
。
然后,您的where
子句正在撤消left join
。您需要将年份的条件移至on
子句:
SELECT . . .
FROM master_months mo LEFT JOIN
orders o
ON mo.month_name = MONTHNAME(o.sale_on) AND
YEAR(o.sale_on) = 2015 LEFT JOIN
order_detail od
ON o.order_id = od.order_id
GROUP BY mo.month_name
ORDER BY mo.month_name