2015-11-08 63 views
0

出現了Oracle數據庫的情況下,我想創建兩個表具有相同的列的報告 表A包括id, code, name和表B包括id, code, name太 現在我想創建一個報告,計數和組數據都表給出結果如下:聚合相同的記錄

Id1, code1, name1, count (the occurrence of this combination in both tables)

Id2, code2, name2, count (the occurrence of this combination in both tables)

我怎麼能achiev e使用查詢得到上述結果?重要的事實是有時某個表中可能找不到特定的項目,因此總計數將是在另一個表中找到的計數。可能的結果將是

idn, coden, namen, count of occurrence which found in one of the tables

回答

2

這樣寫:

SELECT id, code, name, count(*) 
FROM (
    SELECT id, code, name FROM table1 
    UNION ALL 
    SELECT id, code, name FROM table2 
) t 
GROUP BY id, code, name 

如果你想保留的信息如何每個表格中出現多次(id, code, name)組合,可以使用au色譜柱:

SELECT 
    id, 
    code, 
    name, 
    count(*) AS "Occurrence in both tables", 
    count(CASE WHEN t = 'table1' THEN 1 END) AS "Occurrence in table1", 
    count(CASE WHEN t = 'table2' THEN 1 END) AS "Occurrence in table2" 
FROM (
    SELECT id, code, name, 'table1' AS t FROM table1 
    UNION ALL 
    SELECT id, code, name, 'table2' AS t FROM table2 
) t 
GROUP BY id, code, name 
0
select id,name,count from 
(
select id as id , name as name, count as count from table1 
union 
select id as id , name as name, count as count from table2 
) 

,如果你的意思是重要的結果,然後

select count(*) from 
(
    select id,name,count from 
    (
    select id as id , name as name, count as count from table1 
    union 
    select id as id , name as name, count as count from table2 
    ) 
)