ORACLE - 从

时间:2016-07-06 17:46:54

标签: sql oracle count multiple-tables

我共享一个列(day_code编号)的两个表(table1和table2)。

我想从day_code中获取每个表从最小day_code和group得到的记录数。

表1(按day_code记录的数量)

20160703 - 5
20160704 - 4

表2(按day_code记录的数量)

20160703 - 5
20160704 - 4

我需要这样的东西:

----------------------------------------------------
DAY_CODE | TABLE 1 | TABLE 2 |
20160703 |    5    |    5    |
20160704 |    4    |    4    |

我正在使用该查询:

SELECT *
FROM
(
SELECT day_code, COUNT(day_code) AS TB1 FROM TABLE1 GROUP BY day_code
UNION ALL
SELECT day_code, COUNT(day_code) AS TB2 FROM TABLE2 GROUP BY day_code
) s
where day_code between 20160703 and 20160704

我获得了这个:

DAY_CODE  |  TB1
20160703  |   5
20160704  |   4
20160703  |   5
20160704  |   4

你能帮助我吗?

提前感谢您的建议, LR

2 个答案:

答案 0 :(得分:1)

尝试:

SELECT coalesce( t1.day_code, t2.day_code) As daycode,
       nvl( cnt1, 0 ) cnt1,
       nvl( cnt2, 0 ) cnt2
FROM ( 
  SELECT day_code, count(*) cnt1
  FROM tab1
  GROUP BY day_code
) t1
FULL OUTER JOIN ( 
  SELECT day_code, count(*) cnt2
  FROM tab2
  GROUP BY day_code
) t2
ON t1.day_code = t2.day_code
ORDER BY 1

答案 1 :(得分:0)

这是使用pivot的解决方案。我创建了更多数据来显示对空值的正确处理。

with table1 (day_code, ct) as (
       select 20160703, 5 from dual union all
       select 20160704, 4 from dual union all
       select 20160705, 7 from dual
     ),
     table2 (day_code, ct) as (
       select 20160703, 5 from dual union all
       select 20160704, 8 from dual
     )
select *
from (select day_code, ct, 1 as t from table1
      union all
      select day_code, ct, 2 as t from table2
     )
pivot (min(ct) for t in (1 as table1, 2 as table2))
order by day_code;

<强>输出

  DAY_CODE     TABLE1     TABLE2
---------- ---------- ----------
  20160703          5          5
  20160704          4          8
  20160705          7