简体   繁体   中英

How to use sql group by to select top 2 items and sum one field?

for examle, I have data like below, and I want to use group by and limit to select every artist top 2 most stars songs, and sum the stars, but it does not work

select sum(stars) from fav_songs group by artist order by stars desc limit 2;

What the result i wanted is like this:

600 -> taylor swift  
350 -> eminem  
520 -> linkin park  

sqlite3 or mysql both fine

table name :fav_songs

| id | artist       | song           | stars |  
+----+--------------+----------------+-------+  
|  1 | Taylor Swift | Love Story     |   100 |  
|  2 | Taylor Swift | Enchanted      |   200 |  
|  3 | Taylor Swift | Safe and Sound |   400 |  
|  4 | Taylor Swift | Style          |   110 |  
|  5 | Eminem       | 8 Mile         |   200 |  
|  6 | Eminem       | the monster    |   100 |  
|  7 | Eminem       | lose yourself  |   150 |  
|  8 | Linkin Park  | in the end     |   210 |  
|  9 | Linkin Park  | faint          |    90 |  
| 10 | Linkin Park  | numb           |   310 |  

By the way, stackoverflow`s editor does not support table of markdown??

You can use correlated subquery wth aggregation :

select fs.artist, sum(fs.stars) 
from fav_songs fs
where fs.id in (select fs1.id 
                from fav_songs fs1 
                where fs1.artist = fs.artist 
                order by f1.stars desc 
                limit 2
               )
group by fs.artist; 

If your version supports ranking function then you can do :

select fs.artist, sum(fs.stars)
from (select fs.*, 
             row_number() over(partition by fs.artist order by fs.stars desc) as seq
      from fav_songs fs
     ) fs
where fs.seq <= 2
group by fs.artist

If you are running a RDBMS that supports window functions, you can use row number:

select artist, sum(stars)
from (
    select t.*, row_number() over(partition by artist order by stars desc) rn
    from fav_songs
) t
where rn <= 2
group by artist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM