group by משתי טבלאות

e y a l b

New member
group by משתי טבלאות

הטבלאות

cities (c_id int,c_name nvarchar)
table2 (t2_id int,c_id int)
table1(t1_id int ,c_id int)


מנסה לקבל טבלה שבה על כל c_name אני אקבל את מספר השורות מכל אחת מהטבלאות table1 table2


select c_name,count(t2_id) from cities inner join table1 on cities.c_id = table1.c_id
group by c_name


איך אני מחבר את הטבלה השנייה table2?
 

e y a l b

New member
הצלחתי - זאת הדרך הנכונה?

select a.C_Name,a.sum1,isnull(b.sum2,0) sum2 from

(SELECT CITIES.C_Name, COUNT(table1.tb1_ID) AS sum1
FROM CITIES left JOIN
table1 ON CITIES.C_ID = table1.C_ID
GROUP BY CITIES.C_Name) a
left join
(SELECT CITIES.C_Name, COUNT(table2.tb2_ID) AS sum2
FROM CITIES INNER JOIN
table2 ON CITIES.C_ID = table2.C_ID
GROUP BY CITIES.C_Name) b
on a.C_Name = b.C_Name
 

כלליים

New member
לכאורה אפשר כך

select c_name
,(select count(table1.id) from table1 where C_ID = Cities.C_ID) SUM1
,(select count(table1.id) from table1 where C_ID = Cities.C_ID) SUM2
FROM Cities
 
למעלה