表:
a: org1, class, class_id
b: org2, class, class_id
我做了left outer join b on a.class_id = b.class_id
结果:
org1 | org 2 | class
--------+---------+------------------
ENGLISH | ENGLISH | English 101
ENGLISH | ENGLISH | English 220
ENGLISH | COMM | Communication 360
ENGLISH | HISTORY | History 362
HISTORY | ENGLISH | English 366
我想知道是否可以通过SQL实现以下分组,或者使用上面的结果数据集进行编程?
ORG: ENGLISH
-----------------
English 101
English 220
Communication 360
History 362
English 366
-----------------
ORG: HISTORY
-----------------
English 366
History 362
-----------------
COMM
-----------------
Communication 360
答案 0 :(得分:3)
使用UNION
:
SELECT t.org, t.class
FROM
(
SELECT org1 AS org, class
FROM a
UNION ALL
SELECT org2 AS org, class
FROM b
) t
ORDER BY t.org, t.class
编辑:(由戈登)
您不需要子查询:
SELECT org1 AS org, class
FROM a
UNION ALL
SELECT org2 AS org, class
FROM b
ORDER BY org, class;
ORDER BY
适用于union all
的结果。