0

I have two tables A and B. In Table A (Oracle sql), an unique column(not primary key) code may have some records in table B.

Example:

Code "A" has 3 entries, Code "B" has 2 entries and code "C" has 0 entries in table B. I want the query to display the code and its count of records in Table B.

A 3
B 2
C 0, 

But i am not getting the code with zero records in table B, i.e C 0.

Please anyone can help me with the query.

Chiragkumar Thakar
  • 3,616
  • 5
  • 37
  • 49
user3615185
  • 55
  • 1
  • 8

3 Answers3

2

GROUP BY with LEFT JOIN solution:

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

Correlated sub-query solution:

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

Perhaps you need to do SELECT DISTINCT here.

jarlh
  • 42,561
  • 8
  • 45
  • 63
1

You are doing something incorrectly. This works for me:

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

Fiddle: http://sqlfiddle.com/#!4/f13e1/2

Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75
0

It is quite easy, you just need to Take column base on you want count as I did "A.code" and don't forget to Group by that column, and use COUNT(). Check the below solution

   select A.code, Count(B.code) AS Count 
    from A
    left join B on A.code = b.code
    group by A.code
Chiragkumar Thakar
  • 3,616
  • 5
  • 37
  • 49