I need to join 2 tables (Person and PersonLine). The result should contain id
and name
column from Person table and count of personlineid
column from PersonLine Table for each id
. But sql query returns count of all personlineid
. Can anyone help to form the sql.
Person:
ID NAME AGE
100 John 25
101 James 30
102 Janet 35
PersonLine:
ID NAME PERSONLINEID
100 John 1
100 John 2
100 John 3
101 James 1
101 James 2
102 Janet 1
SQL:
SELECT P.ID, CNT.COUNT_PERSONLINE, P.NAME
FROM PERSON P
LEFT JOIN PERSONLINE PL
ON P.ID = PL.ID,
(SELECT count(PL.PERSONLINEID) cnt FROM PERSON P LEFT JOIN PERSONLINE PL ON P.ID = PL.ID WHERE
P.ID = PL.ID) cnt
JOIN Table (Expected):
ID COUNT_PERSONLINE NAME
100 3 John
101 2 James
102 1 Janet
JOIN Table (Actual):
ID COUNT_PERSONLINE NAME
100 6 John
101 6 James
102 6 Janet
With your sample data, you don't even need the
Person
table -- because you seem to have redundant table in the two tables. You should probably fix this, but:Your count is just counting all the rows from the
join
of the tables -- that would be all the rows. A simple aggregation should suffice, even if you decide that thejoin
is still necessary.EDIT:
You have several choices with lots of columns in
persons
. One method is to put them in thegroup by
:Another method is to do the aggregation before the
join
:Or, a correlated subquery: