从两个表中聚合相同的记录

时间:2015-11-08 08:39:27

标签: sql oracle

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)

如何使用查询实现上述结果?重要的事实是,有时某个特定项目可能在一个表中找不到,因此总计数将是在另一个表中找到的计数。可能的结果是

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

2 个答案:

答案 0 :(得分: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)组合出现在每个表中的次数,您可以使用辅助列:

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

答案 1 :(得分:0)

$credential = Get-Credential

如果你想计算结果那么

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
)