我有以下列
Loc_ID | Ctry | Val2 | Val3 |
-------+-------+-------+-------+
1 | 90 | 2.23 | 3.43 |
2 | 90 | 12.23 | Null |
2 | 90 | 9.05 | 13.43 |
4 | 90 | 78.23 | 9.43 |
5 | 91 | 2.23 | 3.43 |
6 | 91 | 12.23 | 2.92 |
7 | 91 | Null | 13.43 |
7 | 91 | 78.23 | 9.43 |
其中Ctry是国家/地区代码。如何找到这两个国家/地区的哪个位置ID最多具有Val2总数
答案 0 :(得分:0)
您可以使用group by
和limit
:
select loc_id, sum(val2) as sum_val2
from t
group by loc_id
order by sum_val2 desc
limit 1;
答案 1 :(得分:0)
我假设您要求在每个国家/地区获得具有最多总val2的位置ID。如果我错了,请纠正。
解决方案如下
WITH v_max_tot
AS
(SELECT Ctry, Loc_ID, SUM(Val2) AS Val2_Total ,
ROW_NUMBER() OVER (PARTITION BY Ctry ORDER BY SUM(Val2) DESC) AS r_num
FROM ramesh_tab
GROUP BY Ctry, Loc_ID)
SELECT Ctry, Loc_ID
FROM v_max_tot
WHERE r_num =1 ;
问题中提供的样本数据的输出如下
Explatnaion
希望这有帮助