将2个结果集合并为一行

时间:2016-04-08 13:28:20

标签: mysql

我有2个结果集,我如何将它们组合在一起以便它们在一行中?

    Result 1:

    North | South| East | West 
    ---------------------------
      5       0      0      5       

    SQL:
    SELECT 
        SUM(CASE WHEN region = 'North' THEN threatlevel ELSE 0 END) AS North,
        SUM(CASE WHEN region = 'South' THEN threatlevel ELSE 0 END) AS South,
        SUM(CASE WHEN region = 'East' THEN threatlevel ELSE 0 END) AS East,
        SUM(CASE WHEN region = 'West' THEN threatlevel ELSE 0 END) AS West,
    FROM incident
    GROUP BY typeOfIncident
    HAVING typeOfIncident LIKE '%H1N5%';


    Result 2:

    North1 | South1 | East1 | West1 
    --------------------------------
      0       5         5       8       

    SQL:
    SELECT
        SUM(CASE WHEN region = 'North' THEN threatlevel ELSE 0 END) AS North1,
        SUM(CASE WHEN region = 'South' THEN threatlevel ELSE 0 END) AS South1,
        SUM(CASE WHEN region = 'East' THEN threatlevel ELSE 0 END) AS East1,
        SUM(CASE WHEN region = 'West' THEN threatlevel ELSE 0 END) AS West1,
    FROM incident
    GROUP BY typeOfIncident
    HAVING typeOfIncident LIKE 'Zombie%';


    OUTPUT:

    North | South | East | West | North1 | South1 | East1 | West1
    --------------------------------------------------------------
      5       0      0      5       0         5       5       8

我尝试过使用union,cross join等。没有返回任何结果。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT 
   SUM(CASE WHEN typeOfIncident LIKE '%H1N5%' AND 
                 region = 'North' THEN threatlevel ELSE 0 END) AS North,
   SUM(CASE WHEN typeOfIncident LIKE '%H1N5%' AND 
                 region = 'South' THEN threatlevel ELSE 0 END) AS South,
   SUM(CASE WHEN typeOfIncident LIKE '%H1N5%' AND 
                 region = 'East' THEN threatlevel ELSE 0 END) AS East,
   SUM(CASE WHEN typeOfIncident LIKE '%H1N5%' AND 
              region = 'West' THEN threatlevel ELSE 0 END) AS West,
   SUM(CASE WHEN typeOfIncident LIKE 'Zombie%' AND
                 region = 'North' THEN threatlevel ELSE 0 END) AS North1,
   SUM(CASE WHEN typeOfIncident LIKE 'Zombie%' AND
                 region = 'South' THEN threatlevel ELSE 0 END) AS South1,
   SUM(CASE WHEN typeOfIncident LIKE 'Zombie%' AND
                 region = 'East' THEN threatlevel ELSE 0 END) AS East1,
   SUM(CASE WHEN typeOfIncident LIKE 'Zombie%' AND
                 region = 'West' THEN threatlevel ELSE 0 END) AS West1
FROM incident