MySQL - 为UNION查询分组

时间:2016-11-08 13:19:47

标签: php mysql phpexcel

我一直试图找到解决我的问题的方法,现在几个小时,但无法提出正确的查询。我有两个表,stocktake_scans和stocktake_items。我需要从两个表中选择数据并将它们组合在一起。我目前的查询是:

SELECT 
a.department_description, a.sub_department_description, a.total_cost, a.total_retail, SUM(a.qty) AS qty, a.total_vat, a.vat_rate 
FROM ( 
    SELECT (CASE WHEN TRIM(IFNULL(sp.department_description, '')) = '' THEN 'N/A' ELSE sp.department_description END) AS department_description, 
    (CASE WHEN TRIM(IFNULL(sp.sub_department_description, '')) = '' THEN 'N/A' ELSE sp.sub_department_description END) AS sub_department_description, 
    SUM(sp.unit_cost_price * ss.quantity) AS total_cost, 
    SUM(sp.unit_retail_price * ss.quantity) AS total_retail, 
    sum(ss.quantity) AS qty, 
    (SUM(sp.unit_cost_price*ss.quantity)) * (sv.vat_rate/100) AS total_vat, 
    sv.vat_rate as vat_rate 
    FROM 
        stocktake_scans ss 
        INNER JOIN stocktake_products sp ON ss.stocktake_product_id = sp.stocktake_product_id 
        LEFT JOIN stocktake_vat_codes sv ON sv.vat_code = sp.vat_code AND sv.stocktake_id = '5778' 
        WHERE ss.stocktake_id = '5778' 
        GROUP BY sp.department_description, sp.sub_department_description 
    UNION ALL 
        SELECT (CASE WHEN TRIM(IFNULL(si.department_description, '')) = '' THEN 'N/A' ELSE si.department_description END) AS department_description, 
        'N/A' as sub_department_description, 
        SUM(si.unit_cost_price * si.quantity) AS total_cost, 
        SUM(si.unit_retail_price * si.quantity) AS total_retail, 
        sum(si.quantity) AS qty,
        SUM(si.unit_cost_price * quantity)*(sv.vat_rate/100) AS total_vat, 
        sv.vat_rate as vat_rate 
        FROM stocktake_items si 
        LEFT JOIN stocktake_vat_codes sv ON sv.vat_code = si.vat_code AND sv.stocktake_id = '5778' 
        WHERE si.stocktake_id = '5778' GROUP BY si.department_description ) a 
    GROUP 
        BY a.department_description, a.sub_department_description

这不能完全胜任这项工作。我从stocktake_scans获得所有数据,然后是stocktake_items的数据。

我得到以下作为第一个结果 Image 1

然后在excel文件的末尾我也得到了这个

Image 2

这样做的正确方法是什么,以便将酒精数字显示在一个地方?

1 个答案:

答案 0 :(得分:0)

在最后ORDER BY a.department_description, a.sub_department_description

之前添加GROUP BY