elena1234

Highest Peak and Longest River by Country - with CTE ( T-SQL )

Dec 31st, 2021 (edited)
519
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.36 KB | None | 0 0
  1. --17.Highest Peak and Longest River by Country from Subqueries and Joins
  2. USE Geography
  3. WITH CTE_PEAKS (CountryCode, CountryName, MountainRange, PeakName, Elevation, RANK_PEAKS) AS
  4.      (
  5.       SELECT Countries.CountryCode, Countries.CountryName, Mountains.MountainRange, Peaks.PeakName, Peaks.Elevation,
  6.       DENSE_RANK() OVER(PARTITION BY Countries.CountryName ORDER BY Peaks.Elevation DESC) AS RANK_PEAKS
  7.       FROM Countries
  8.       LEFT JOIN MountainsCountries ON MountainsCountries.CountryCode = Countries.CountryCode
  9.       LEFT JOIN Mountains ON Mountains.Id = MountainsCountries.MountainId
  10.       LEFT JOIN Peaks ON Peaks.MountainId = Mountains.Id
  11.      ),
  12.      CTE_RIVERS (CountryCode, RiverName, RiverLength, RANK_RIVERS) AS
  13.      (
  14.       SELECT Countries.CountryCode, Rivers.RiverName, Rivers.Length AS  RiverLength,
  15.       DENSE_RANK() OVER(PARTITION BY Countries.CountryName ORDER BY Rivers.Length DESC) AS RANK_RIVERS
  16.       FROM Countries
  17.       LEFT JOIN CountriesRivers ON CountriesRivers.CountryCode = Countries.CountryCode
  18.       LEFT JOIN Rivers ON Rivers.ID = CountriesRivers.RiverId
  19.      )
  20. SELECT TOP(5) CountryName, Elevation AS HighestPeakElevation, RiverLength AS LongestRiverLength
  21. FROM CTE_PEAKS
  22. LEFT JOIN  CTE_RIVERS ON CTE_RIVERS.CountryCode = CTE_PEAKS.CountryCode
  23. WHERE RANK_RIVERS = 1 AND RANK_PEAKS = 1
  24. ORDER BY Elevation DESC, RiverLength DESC, CountryName;
  25.  
Add Comment
Please, Sign In to add comment