user380432
user380432

Reputation: 4779

INNER JOIN Distinct ID

I have the following code:

FROM CTE_Order cte
    INNER JOIN tblOrders o
       ON cte.OrderId = o.Id
    INNER JOIN tblOrderUnits ou
       ON o.id = ou.OrderId                        
    INNER JOIN tblOrderServiceUnits osu
       ON ou.VMSUnitID = osu.UnitId

When I join the ou I get 2 of the same unit Id's. This make the Inner Join tblOrderServiceUnits return 4 rows with 2 being duplicates. I need it to only return the 2 rows the are different. How do I use a distinct to Inner Join only distinct ou.id?

Sorry for the bad explanation but basically I am jsut trying to see how an INNER JOIN with a distinct subquery would work, If someone could give me an example of that I could figure it out from there.

Upvotes: 8

Views: 26751

Answers (1)

Chuck Callebs
Chuck Callebs

Reputation: 16441

INNER JOIN (SELECT DISTINCT * FROM X) Alias
ON Alias.ID = Primary.ID

For your example:

INNER JOIN (SELECT DISTINCT VMSUnitID, OrderId FROM tblOrderUnits) ou
ON o.id = ou.OrderId

Upvotes: 20

Related Questions