SQL 查询 - 查找相同 table 中 2 个值之间的差异

SQL Query - Finding a difference between 2 values in same table

我需要有关涉及我的一个数据库的特定查询的帮助。

Name           Elev    Difficulty  Map         Region
----------------------------------------------------------
Pilot Knob(S)   6200    2       Oynx          Southern Sierra
Spanish Needle  12322   3       Lament Peak   Southern Sierra
Lamont Peak     7429    2       Lament Peak   Southern Sierra
South Guard     13232   2       Mt Brewer     Great Western Divide
Mount Brewer    13570   2       Mt Brewer     Great Western Divide
North Guard     13327   4       Mt Brewer     Great Western Divide
Midway Mountain 11284   2       Mt Brewer     Great Western Divide

我需要找出哪些地图的最高山峰和最低山峰之间的差异超过 2000 英尺?

不确定我会使用 MIN() 和 MAX() 函数来解决这个问题。 非常感谢您的帮助!

您在 MIN 和 MAX 方面走在正确的轨道上。您只需要将它们应用于一组地图。像这样:

SELECT Map 
FROM 
    Table 
GROUP BY  
    Map
HAVING 
    MAX(Elev) - MIN(Elev) > 2000
ORDER BY
    MAX(Elev) - MIN(Elev) 

取决于您的实施(我已经在下面的 T-SQL 中演示了写作。您需要将地图聚合到组中,然后根据这些分组中的最大值和最小值来评估它们。

--//We're grouping by map and demonstrating the max and min values returned
select Map, max (elev) as MaxElev, min (elev) as MinElev
from targettable
group by map;

--//We then need to filter the group and only return when the difference is
--//Greater than 2000
select map,  max (elev) as MaxElev, min (elev) as MinElev
from targettable
group by map
having (Max (elev) - 2000) > min (Elev);

--//Or alternatively you can use subtract values and compare

select map,  max (elev) as MaxElev, min (elev) as MinElev
from targettable
group by map
having (max (elev) - min (elev)) > 2000;

--//We can then tidy up and add an order if required (descending shown)

select map
from targettable
group by map
having (max (elev) - min (elev)) > 2000
order by max(elev);