Mahdi Radi
Mahdi Radi

Reputation: 439

How Multiple Joins on Multiple Tables in One Query At SQL Server

I work on a C# project that uses SQL Server.

I want to join on multiple tables in a query (OR run multiple statements in a single query)

My query is this :

(select HR.ID, HR.Cod, HR.CodeValed, H.Onvan, H.Model from HR LEFT JOIN H ON HR.ID_Sefat = H.ID) AAA;
SELECT GG.Cod G
FROM 
(Select * From AAA Where AAA.Model = 'M') MM
Left JOIN (Select * From AAA Where AAA.Model = 'K') KK ON MM.CodeValed = KK.Cod
Left JOIN (Select * From AAA Where AAA.Model = 'G') GG ON KK.CodeValed = GG.Cod

But it doesn't work, it returns an error.

What is the best way to solve this problem?

Upvotes: 0

Views: 442

Answers (1)

Ravi Singh
Ravi Singh

Reputation: 2080

Try this :

with AAA as 
(select HR.ID, HR.Cod, HR.CodeValed, H.Onvan, H.Model from HR 
LEFT JOIN H ON HR.ID_Sefat = H.ID) 
SELECT GG.Cod G
FROM 
(Select * From AAA Where AAA.Model = 'M') MM
Left JOIN (Select * From AAA Where AAA.Model = 'K') KK ON MM.CodeValed = KK.Cod
Left JOIN (Select * From AAA Where AAA.Model = 'G') GG ON KK.CodeValed = GG.Cod

Upvotes: 2

Related Questions