SQL(oracle) - 如何从多个表中查询多个更改的值

时间:2017-10-30 20:15:20

标签: sql oracle

我正在尝试对多个表中指定时间段内更改的所有值进行审核。有没有更简单的方式写下面的?

select property_number, 'table1', count(*)
    from table1
   where start_date between to_date('07/01/2017','mm/dd/yyyy') and to_date('09/30/2017', 'mm/dd/yyyy')
group by property_number
union all
  select property_number, 'table2', count(*)
    from table2
   where start_date between to_date('07/01/2017', 'mm/dd/yyyy') and to_date('09/30/2017', 'mm/dd/yyyy')
group by property_number
union all
  select property_number, 'table3', count(*)
    from table3
   where start_date between to_date('07/01/2017', 'mm/dd/yyyy') and to_date('09/30/2017', 'mm/dd/yyyy')
group by property_number
union all
  select property_number, 'table4', count(*)
    from table4
   where start_date between to_date('07/01/2017', 'mm/dd/yyyy') and to_date('09/30/2017', 'mm/dd/yyyy')
group by property_number
union all
  select property_number, 'table5', count(*)
    from table5
   where start_date between to_date('07/01/2017', 'mm/dd/yyyy') and to_date('09/30/2017', 'mm/dd/yyyy')
group by property_number

1 个答案:

答案 0 :(得分:2)

考虑使用DRE-er解决方案的CTE。

WITH master_all AS
  (SELECT property_number, 'table1' AS "indicator"
   FROM table1
   UNION ALL 
   SELECT property_number, 'table2'
   FROM table2
   UNION ALL 
   SELECT property_number, 'table3'
   FROM table3
   UNION ALL 
   SELECT property_number, 'table4'
   FROM table4
   UNION ALL 
   SELECT property_number, 'table5'
   FROM table5)

SELECT property_number, indicator, Count(*) AS "Audit_Count"
FROM  master_all
WHERE start_date BETWEEN to_date('07/01/2017', 'mm/dd/yyyy') 
                     AND to_date('09/30/2017', 'mm/dd/yyyy')
GROUP BY property_number, indicator;

但是再一次考虑一个模式调整,并将所有类似的带有指标字段的结构化表附加到一个主表中。