如何通过某些标准MS SQL选择组的一部分

时间:2015-07-11 19:33:47

标签: sql sql-server grouping

我有以下任务: 我们有以下MS SQL表: 国家/地区 - 拥有ID和CountryName, MountainsCountries--在国家和山脉之间创造了多对多的关系 山脉 - 有ID和MountainName 峰值 - 具有Id,PeakName和Mountain ID。因此,我们将Mountain - Peak视为一对多关系。

我们需要找到每个国家/地区的最高峰值,并将其与名称一起显示。每当一个国家没有山峰或山峰没有山峰时,我们也需要显示null。如果有两个具有相同高程的最高峰,我们必须显示两个峰。结果必须看起来像

国家最高峰名称最高峰海拔山 阿富汗NULL NULL NULL 阿根廷阿空加瓜6962安第斯山脉 保加利亚Musala 2925 Rila

如果我们不需要显示峰值,我可以完成任务。名。但我现在无法解决这个问题。当我创建GROUP BY Country和mountain时,如何选择最高峰?我在考虑ROW_NUMBER()OVER(PARTITION BY ...),但它只会返回第一个最高峰。因此,如果我们有两个相同高度的峰值,我们将不会同时采取这两个峰值。到目前为止,这是我的代码:

SELECT c.CountryName, p.PeakName, MAX(p.Elevation) AS [HighestPeakElevation], m.MountainRange AS [Mountain]
FROM Countries c 
LEFT OUTER JOIN MountainsCountries mc ON c.CountryCode = mc.CountryCode
LEFT OUTER JOIN Mountains m ON m.Id = mc.MountainId
LEFT OUTER JOIN Peaks p ON p.MountainId = m.Id
GROUP BY CountryName, MountainRange
??????????
HAVING p.Elevation = MAX(p.Elevation) ???

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

SELECT c.CountryName, p.PeakName, p.Elevation AS [HighestPeakElevation], m.MountainRange AS [Mountain]
FROM Countries c 
LEFT OUTER JOIN MountainsCountries mc ON c.CountryCode = mc.CountryCode
LEFT OUTER JOIN Mountains m ON m.Id = mc.MountainId
LEFT OUTER JOIN Peaks p ON p.MountainId = m.Id 
HAVING p.Elevation = MAX(p.Elevation) OVER (PARTITION BY c.CountryName, m.MountainRange)

或者

SELECT CountryName, PeakName, HighestPeakElevation, Mountain FROM (SELECT c.CountryName AS CountryName, p.PeakName AS PeakName, p.Elevation AS PeakElevation, MAX (p.Elevation) OVER (PARTITION BY c.CountryName, m.MountainRange) AS [HighestPeakElevation], m.MountainRange AS [Mountain]
FROM Countries c 
LEFT OUTER JOIN MountainsCountries mc ON c.CountryCode = mc.CountryCode
LEFT OUTER JOIN Mountains m ON m.Id = mc.MountainId
LEFT OUTER JOIN Peaks p ON p.MountainId = m.Id) AS t WHERE PeakElevation = HighestPeakElevation