【问题标题】:display Count of one column from another table even when the count is zero显示另一个表中一列的计数,即使计数为零
【发布时间】:2015-07-07 11:08:37
【问题描述】:

我有两张桌子 A 和 B。在表A(Oracle sql)中,唯一列(不是主键)code可能在表B中有一些记录。

示例:

代码“A”有 3 个条目,代码“B”有 2 个条目,代码“C”在表 B 中有 0 个条目。我希望查询显示代码及其在表 B 中的记录数。

A 3
B 2
C 0, 

但我没有得到表 B 中记录为零的代码,即 C 0。

请任何人都可以帮助我进行查询。

【问题讨论】:

  • 使用 GROUP BY 进行 LEFT JOIN,然后计数。
  • 我试过了..但没有正确理解..请告诉我上述场景的确切查询
  • 向我们展示示例表数据、您的查询(无法正常工作的查询)和预期结果!
  • SAmple 表 A 代码名称 A pal B john C APril 表 B 代码值 A 10 A 20 B 30 样本输出:代码 NoofEntries A 2 B 1 C 0
  • 我的查询: select a.code,a.name,count(b.code) from A a, B b where a.code=b.code group by a.code, a.name;

标签: sql oracle left-join nvl


【解决方案1】:

GROUP BYLEFT JOIN 解决方案:

select a.code,
       a.name,
       count(*)
from A a
  LEFT JOIN B b ON a.code = b.code
group by a.code, a.name

相关子查询解决方案:

select a.code,
       a.name,
       (select count(*) from B b where a.code = b.code)
from A a

也许你需要在这里做SELECT DISTINCT

【讨论】:

    【解决方案2】:

    你做错了什么。这对我有用:

    select A.code, Count(B.code) from A
    left join B on A.code = b.code
    group by A.code
    

    小提琴:http://sqlfiddle.com/#!4/f13e1/2

    【讨论】:

    • 这是完美的解决方案
    【解决方案3】:

    这很简单,你只需要像我一样根据你想要计数的列来计算 "A.code" 并且不要忘记按该列分组,然后使用 计数()。 检查以下解决方案

       select A.code, Count(B.code) AS Count 
        from A
        left join B on A.code = b.code
        group by A.code
    

    【讨论】:

      猜你喜欢
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多