Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- WITH cte (CountryName, Count)
- AS
- (
- SELECT sub.CountryName, MAX(sub.Count)
- FROM (SELECT coun.Name AS [CountryName],
- d.Name AS [DistributorName],
- COUNT(*) AS [Count]
- FROM Countries AS coun
- LEFT OUTER JOIN Distributors AS d
- ON d.CountryId = coun.Id
- LEFT OUTER JOIN Ingredients AS i
- ON i.DistributorId = d.Id
- GROUP BY coun.Name, d.Name) AS sub
- GROUP BY sub.CountryName
- )
- SELECT coun.Name AS [CountryName],
- d.Name AS [DistributorName]
- FROM Countries AS coun
- LEFT OUTER JOIN Distributors AS d
- ON d.CountryId = coun.Id
- LEFT OUTER JOIN Ingredients AS i
- ON i.DistributorId = d.Id
- GROUP BY coun.Name, d.Name
- HAVING COUNT(*) IN (SELECT cte.Count FROM cte WHERE coun.Name = cte.CountryName)
- ORDER BY coun.Name, d.Name
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement