【问题标题】:ORACLE - Count from two tables with group byORACLE - 从两个表中按分组计数
【发布时间】:2016-07-06 17:46:53
【问题描述】:

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

我想从最小的 day_code 中获取每个表的记录数,并按 day_code 的结果分组。

表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

你能帮帮我吗?

提前感谢您的建议, 左路

【问题讨论】:

  • 不完全清楚你的输出要求是什么。具有管道分隔值的单个单行字符串?包含列标题 DAY_CODE、TABLE 1 和 TABLE 2 以及每个 DAY_CODE 一行的行表?
  • 对不起@mathguy。但我已经有了我想要的。 kordirko 的回答是正确的。 ;)
  • 明白。 a_horse 的编辑有所帮助。我也给出了答案。请将 kordiko 的答案标记为“正确”(他发布了他的第一个);但在你这样做之后,你可能想尝试这两个答案,看看哪个在你的特定情况下效果更快。

标签: sql oracle count multiple-tables


【解决方案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

【讨论】:

  • 谢谢@kordiko。这是完美的! ;)
  • 我很高兴我能帮上忙。如果你喜欢这个答案,请采纳,谢谢。
【解决方案2】:

这是一个使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 2023-04-01
    • 1970-01-01
    • 2020-12-24
    • 2012-03-30
    • 2017-06-22
    相关资源
    最近更新 更多