2016-03-31 438 views
0

我需要涉及我的某個數據庫的特定查詢的幫助。SQL查詢 - 查找同一個表中的兩個值之間的差異

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()函數來解決這個問題。 非常感謝幫助!

+1

請與標記您正在使用的數據庫和提示你的問題:使用'HAVING'條款 –

+0

我有不同的解決方案,你,但我不能,除非你標記你正在使用的數據庫 – Licantropo

+0

。使用oracle express。 – Scott

回答

2

您在MIN和MAX的正確軌道上。你只需要將它們應用於一組地圖。事情是這樣的:

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

非常感謝!作品完美。 – Scott

+0

很高興幫助!Remem如果您不需要更多的答案,可以將其標記爲答案。 – user2316154

+0

無論如何要列出結果至少以最大的秩序? – Scott

0

根據您的實現(我已經證明了在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); 
相關問題