Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

sql - How can i get top row in partition?

Sport Athlete Year Medal
hockey COWLEY, Gillian Margaret 1980 Gold
hockey DAVIES, Patricia Joan 1980 Gold
rowing REIC, Josip 1980 Bronze
Aquatics COVENTRY, Kirsty 2004 Silver
Boxing SKARO, Damir 1988 Bronze
Boxing KACAR, Slobodan 1980 Gold
question from:https://stackoverflow.com/questions/65946344/how-can-i-get-top-row-in-partition

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One method is a subquery:

SELECT t.*
FROM (SELECT ROW_NUMBER() over (PARTITION BY Sport ORDER BY Athlete ) as rn, Athlete, Event 
      FROM `table`
     ) t
WHERE rn = 1;

A more colloquial way to do this in BQ uses aggregation, though:

select array_agg(t order by athlete asc limit 1)[ordinal(1)].*
from `table` t
group by sport;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...