分组并计算不返回我的期望

时间:2016-04-07 22:49:19

标签: mysql sql group-by

我有这张桌子,我需要知道艺术家在他/她的职业生涯中有多少张专辑,为了简洁起见,我只发布一位艺术家。

"artist_ID" "song_ID" "album_ID" "touring"
"57"      "98"       "48"      "No"        
"57"      "99"       "48"      "No"        
"57"      "100"      "48"      "Sí"        
"57"      "101"      "48"      "No"        
"57"      "102"      "48"      "No"        
"57"      "103"      "48"      "No"        
"57"      "104"      "48"      "No"        
"57"      "105"      "48"      "No"        
"57"      "106"      "48"      "No"        
"57"      "279"      "163"     "No"        
"57"      "280"      "163"     "No"        
"57"      "281"      "163"     "No"        
"57"      "380"      "241"     "No"        
"57"      "381"      "241"     "No"        

然后通过这个获取数据:

SELECT artist_ID,
    count(*) AS churned_albums
FROM relation
GROUP BY group_ID,
    album_ID;

我希望得到以下数据:

"artist_ID" "churned_albums"           
"57"      "3"                     

但是,唉,我明白了:

"artist_ID" "churned_albums"
"57"      "9"             
"57"      "3"             
"57"      "2"             

它正在计算每张专辑的每首歌曲,我不知道如何告诉MySQL忽略这些歌曲,只计算专辑。我还尝试count(artist_ID)而不是count(*)以及其他几种排列,但似乎没有任何效果。

此问题与How to use count and group by at the same select statementUsing group by on multiple columns密切相关,但它们没有帮助。 :(

感谢您的帮助! :)

2 个答案:

答案 0 :(得分:2)

我创建了一个 sqlfiddle ,用于显示所需的查询。看看这里:http://sqlfiddle.com/#!9/d1372/2

我使用的查询:

select group_id, count(distinct album_id) AS churned_albums
from relations
group by group_id;

答案 1 :(得分:1)

您可以使用count(distinct album_id)计算每group_id

个唯一相册的数量
select group_id,
    count(distinct album_id) as churned_albums
from relation
group by group_id