Advertisement
Guest User

Rivers by Country

a guest
Jun 20th, 2015
463
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 1.25 KB | None | 0 0
  1. /*Problem 9.    Rivers by Country
  2. For each country in the database, display the number of rivers passing through
  3. that country and the total length of these rivers. When a country does not have
  4. any river, display 0 as rivers count and as total length. Sort the results by
  5. rivers count (from largest to smallest), then by total length (from largest
  6. to smallest), then by country alphabetically.*/
  7.  
  8. --MY SOLUTION:
  9.  
  10. SELECT
  11.     C.CountryName,
  12.     CN.ContinentName,
  13.     COUNT(R.RiverName) AS [RiversCount],
  14.     ISNULL(SUM(R.LENGTH), 0) AS [TotalLength]
  15. FROM Rivers R
  16. JOIN CountriesRivers CR
  17. ON CR.RiverId = R.Id
  18. RIGHT OUTER JOIN Countries C
  19. ON C.CountryCode = CR.CountryCode
  20. JOIN Continents CN
  21. ON CN.ContinentCode = C.ContinentCode
  22. GROUP BY C.CountryName, CN.ContinentName
  23. ORDER BY RiversCount DESC, TotalLength DESC, C.CountryName
  24.  
  25. --AUTHOR SOLUTION
  26.  
  27. SELECT
  28.   c.CountryName, ct.ContinentName,
  29.   COUNT(r.RiverName) AS RiversCount,
  30.   ISNULL(SUM(r.LENGTH), 0) AS TotalLength
  31. FROM
  32.   Countries c
  33.   LEFT JOIN Continents ct ON ct.ContinentCode = c.ContinentCode
  34.   LEFT JOIN CountriesRivers cr ON c.CountryCode = cr.CountryCode
  35.   LEFT JOIN Rivers r ON r.Id = cr.RiverId
  36. GROUP BY c.CountryName, ct.ContinentName
  37. ORDER BY RiversCount DESC, TotalLength DESC, CountryName
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement