MySQL在一个表上合并两个带有CASE的SELECT查询

时间:2015-01-26 13:45:14

标签: mysql select join merge union

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

1ST QUERY(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

2ND QUERY(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

1 个答案:

答案 0 :(得分:1)

您可以在CASE

中使用SUM()
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