f1 f2 f3
----------------
10 20 30
10 15 50
11 12 25
11 79 13
按f1分组,如何获得最大f2及其对应的f3?
f1 f2 f3
----------------
10 20 30
11 79 13
答案 0 :(得分:1)
您可以使用带有row_number的cte,按f1分区并仅选择每个的第一行(按f2 desc排序,这将为您提供最大f2)
with cte as (select
f1,
f2,
f3,
row_number() over(partition by f1 order by f2 desc) rn
from t)
select
f1,
f2,
f3
from cte
where rn = 1
请参阅SqlFiddle
答案 1 :(得分:1)
您想使用row_number()
:
select t.*
from (select t.*, row_number() over (partition by f1 order by f2 desc) as seqnum
from table t
) t
where seqnum = 1;
答案 2 :(得分:1)
你也可以使用这个(没有RN):
SELECT DISTINCT a.f1,x.f2,x.f3
FROM YourTable a
CROSS APPLY (SELECT TOP 1 f2,f3
FROM YourTable b
WHERE a.f1 = b.f1 ORDER BY b.f2 DESC) x
答案 3 :(得分:1)
你可以这样做
SELECT t1.f1
, t.f2
, t1.f3
FROM tbl t1
cross apply (SELECT max(f2) f2
FROM tbl
GROUP BY f1) t
WHERE t1.f2=t.f2