Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
I have 3 tables with 1 to many relationship as discribed belowTable ACompanyId CompanyName1 ABC2 BCD3 XYZ4 TTTTable BCompanyId LocationId1 a1 b2 c3 dTable CLocationId DepartmentIda ita hra elb ghc trI want to write a query scan the Table A to display row in table A and # of Location and Department belong to the Company, like this:CompanyId CompanyName # of Location # of Department1 ABC 2 42 BCD 1 13 XYZ 1 04 TTT 0 0Please help meThanks
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2008-06-12 : 13:54:23
[code]SELECT a.CompanyId,a.CompanyName,COUNT(DISTINCT b.LocationId) AS [# of Location],COUNT(DepartmentId) AS [# of Department]FROM TableA aINNER JOIN TableB bON b.CompantId=a.CompanyIdINNER JOIN TableC cON c.LocationId=b.LocationIdGROUP BY a.CompanyId,a.CompanyName[/code]
maxovn
Starting Member
3 Posts
Posted - 2008-06-12 : 15:08:28
Good ThanksBut result missing 2 rowsHere is the result when runing that script-----------------------1 ABC 2 42 BCD 1 1-----------------------
chiragkhabaria
Master Smack Fu Yak Hacker
1907 Posts
Posted - 2008-06-12 : 15:41:10
I guess you require to use left outer join...
SELECT a.CompanyId,a.CompanyName,COUNT(DISTINCT b.LocationId) AS [# of Location],COUNT(DepartmentId) AS [# of Department]FROM TableA aLEFT OUTER JOIN TableB bON b.CompantId=a.CompanyIdLEFT OUTER TableC cON c.LocationId=b.LocationIdGROUP BY a.CompanyId,a.CompanyName
Chiraghttp://www.chirikworld.com
maxovn
Starting Member
3 Posts
Posted - 2008-06-12 : 16:04:06
Yes, you are right.To get all rows, we have to use left outer join.Thanks ALL