MySQL 合并两个 SELECT CASE 查询 Table

MySQL Merge Two SELECT Queries With CASE On One Table

我想将两个查询合并为一个完整的查询。我需要将两个查询分组到一个聚合字段 (MFG) 上。我会假设你使用 JOIN 但它在同一个 table 上并且带有 CASE 所以我不确定它是如何工作的。

第一次查询 (2015)

SELECT 
    CASE
        WHEN ITEM LIKE '%1%' THEN 'MFG1'
        WHEN ITEM LIKE '%2%' THEN 'MFG2'
        WHEN ITEM LIKE '%3%' THEN 'MFG3'
        ELSE ''
    END AS MFG,
    SUM(COST) AS Cost2015
FROM
    table
WHERE
    TRANS_DATE BETWEEN '2015-12-01' AND '2015-12-31'
GROUP BY MFG

第二次查询 (2014)

SELECT 
    CASE
        WHEN ITEM LIKE '%1%' THEN 'MFG1'
        WHEN ITEM LIKE '%2%' THEN 'MFG2'
        WHEN ITEM LIKE '%3%' THEN 'MFG3'
        ELSE ''
    END AS MFG,
    SUM(COST) AS Cost2014
FROM
    table
WHERE
    TRANS_DATE BETWEEN '2014-12-01' AND '2014-12-31'
GROUP BY MFG

期望的结果

MFG  |  Cost2015  |  Cost2014
MFG1 |   1500     |     0
MFG2 |   1000     |    1200
MFG3 |     0      |    3600
     |    100     |     15

您可以在 SUM()

中使用 CASE
SELECT 
    CASE
        WHEN ITEM LIKE '%1%' THEN 'MFG1'
        WHEN ITEM LIKE '%2%' THEN 'MFG2'
        WHEN ITEM LIKE '%3%' THEN 'MFG3'
        ELSE ''
    END AS MFG,
    SUM(CASE WHEN TRANS_DATE BETWEEN '2014-12-01' AND '2014-12-31' THEN COST ELSE 0 END) AS Cost2014,
    SUM(CASE WHEN TRANS_DATE BETWEEN '2015-12-01' AND '2015-12-31' THEN COST ELSE 0 END) AS Cost2015
FROM
    TABLE
WHERE
    TRANS_DATE BETWEEN '2014-12-01' AND '2015-12-31'
GROUP BY MFG