Advertisement
simonradev

da

Oct 18th, 2017
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 0.76 KB | None | 0 0
  1. WITH cte (CountryName, Count)
  2. AS
  3. (
  4.     SELECT sub.CountryName, MAX(sub.Count)
  5.     FROM (SELECT coun.Name AS [CountryName],
  6.                  d.Name AS [DistributorName],
  7.                  COUNT(*) AS [Count]
  8.           FROM Countries AS coun
  9.           LEFT OUTER JOIN Distributors AS d
  10.           ON d.CountryId = coun.Id
  11.           LEFT OUTER JOIN Ingredients AS i
  12.           ON i.DistributorId = d.Id
  13.           GROUP BY coun.Name, d.Name) AS sub
  14.           GROUP BY sub.CountryName
  15. )
  16.  
  17. SELECT coun.Name AS [CountryName],
  18.      d.Name AS [DistributorName]
  19. FROM Countries AS coun
  20. LEFT OUTER JOIN Distributors AS d
  21. ON d.CountryId = coun.Id
  22. LEFT OUTER JOIN Ingredients AS i
  23. ON i.DistributorId = d.Id
  24. GROUP BY coun.Name, d.Name
  25. HAVING COUNT(*) IN (SELECT cte.Count FROM cte WHERE coun.Name = cte.CountryName)
  26. ORDER BY coun.Name, d.Name
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement