如何组合多个查询?

时间:2017-09-15 09:36:36

标签: sql oracle

我有一些类似的问题:

select sysdate from dual;
select id, count(*) as A from TABLE1 group by id;
select id, count(*) as B from TABLE2 group by id;
select id, count(*) as C from TABLE3 group by id;
select id, count(*) as D from TABLE4 group by id;

如何组合这5个查询:

enter image description here

谢谢。

2 个答案:

答案 0 :(得分:2)

您可以以有意义的方式将四个表联合在一起,然后进行条件聚合:

SELECT
    SYSDATE,
    id,
    SUM(CASE WHEN label = 'A' THEN 1 ELSE 0 END) AS A,
    SUM(CASE WHEN label = 'B' THEN 1 ELSE 0 END) AS B
    SUM(CASE WHEN label = 'C' THEN 1 ELSE 0 END) AS C,
    SUM(CASE WHEN label = 'D' THEN 1 ELSE 0 END) AS D
FROM
(
    SELECT id, 'A' AS label
    FROM TABLE1
    UNION ALL
    SELECT id, 'B'
    FROM TABLE2
    UNION ALL
    SELECT id, 'C'
    FROM TABLE3
    UNION ALL
    SELECT id, 'D'
    FROM TABLE4
) t
GROUP BY id;

答案 1 :(得分:0)

使用union关键字。

来使用此功能