【问题标题】:Select sum if and having count选择总和如果并且有计数
【发布时间】:2020-03-12 10:36:56
【问题描述】:

我有 3 张桌子 具有 artist_idname 的表艺术家;

带有album_idartist_idname的专辑;

带有 song_idartist_idalbum_id 的表格歌曲(还有一些东西,但我认为它们对于这个问题没有必要) ;

我想选择一个表格,其中包含艺术家的姓名、包含等于或多于 10 首歌曲的专辑数量、少于 10 首歌曲的专辑数量。

计算每张专辑的歌曲数量是这样的:

select album.name, count(DISTINCT songs.song_id)
from album inner join faixas on album.album_id = songs.album
group by album.name

现在我知道,如果在某个地方出现这样的情况,我将不得不进行求和,并进行超过 1 次选择,只是看不到如何连接两者

sum(if(count (song_id)>=10,1,0)) and sum(if(count (song_id)<10,1,0))

【问题讨论】:

    标签: mysql sql phpmyadmin


    【解决方案1】:

    我认为您需要两个级别的聚合,外层有条件聚合:

    select a.artist_id, a.name,
           sum(num_songs >= 10) as cnt_10_plus,
           sum(num_songs < 10) as cnt_9_minus,
    from artists a join
         album al
         on al.artist_id = a.artist_id join
         (select s.album_id, count(*) as num_songs
          from songs s
          group by s.album_id
         ) s
         on al.album_id = s.album_id
    group by a.artist_id, a.name;
    

    【讨论】:

    • 除了 n al.album_id = a.album_id join 必须与 Artist_id 和小细节改变它的工作。非常感谢!
    猜你喜欢
    • 2020-02-15
    • 2018-06-20
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    相关资源
    最近更新 更多