Mysql:选择2表并根据年份将其显示为列

时间:2016-10-05 01:51:42

标签: mysql sql

我的表格看起来像这样:

表A:

YEAR | GenerationA | TransmissionA
--------------------------------
2015 | 213         | null
2016 | 1122        | null
2016 | null        | 5
2017 | null        | 999

tableB的:

YEAR | GenerationB | TransmissionB
--------------------------------
2014 | 111         | null
2016 | 534         | null
2016 | null        | 4
2017 | null        | 5
2017 | 555         | null

对于表A和B,数据将出现在Generation或Transmission列中,它不能同时为列。

例如,TableA,2016年,第1个数据出现在生成列534,2016年的第2个数据将出现在值4的变量列中。 其中一些将在生成或传输中出现一次

结果

我想根据年份加入这个2表,以便它成为如下结果:

YEAR | GenerationA | TransmissionA | GenerationB | TransmissionB
----------------------------------------------------------------------------------------
2014 | null        | null          | 111         | null
2015 | 213         | null          | null        | null
2016 | 1122        | 5             | 534         | 4
2017 | null        | 999           | 555         | 5

架构:

我试图在sqlfiddle上创建它,它一直给我错误,所以这就是它:

CREATE TABLE tableA
(
Year int(11),
GenerationA int(20),
TransmissionA int(20)
);

CREATE TABLE tableB
(
Year int(11),
GenerationB int(20),
TransmissionB int(20)
);

INSERT INTO tableA VALUES (2015,213,null);
INSERT INTO tableA VALUES (2016,1122,null);
INSERT INTO tableA VALUES (2016,null,5);
INSERT INTO tableA VALUES (2017,null,999);

INSERT INTO tableB VALUES (2014,111,null);
INSERT INTO tableB VALUES (2016,534,null);
INSERT INTO tableB VALUES (2016,null,4);
INSERT INTO tableB VALUES (2017,null,5);
INSERT INTO tableB VALUES (2017,555,null);

SQL方法:

SELECT * FROM tableA
LEFT JOIN tableB ON tableA.YEAR = tableB.YEAR
GROUP BY tableA.YEAR
UNION
SELECT * FROM tableA
RIGHT JOIN tableB ON tableA.YEAR = tableB.YEAR
GROUP BY tableB.YEAR

尝试上面的sql,但无法得到结果。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

您可以使用union allgroup by

执行此操作
select year,
       max(GenerationA) as GenerationA,
       max(TransmissionA) as TransmissionA,
       max(GenerationB) as GenerationB,
       max(TransmissionB) as TransmissionB
from ((select year, GenerationA, TransmissionA, 
              NULL as GenerationB, NULL as TransmissionB
       from tableA
      ) union all
      (select year, NULL as GenerationA, NULL as TransmissionA, 
              GenerationB, TransmissionB
       from tableB
      )
     ) ab
group by year;