MySql选择distinct与sum产生奇怪的结果

时间:2014-11-14 03:03:58

标签: mysql sql

我正在尝试选择不同的tagName以及这些tagNames的总和,但似乎只获得了一个结果。

"gId"   "tagName"           "tagTotal"  "tagCountryCode"
"1"     "metallica"         "5"         "US"
"2"     "abba"              "5"         "US"
"3"     "metallica"         "1"         "US"
"4"     "abba"              "1"         "US"
"5"     "metallica"         "1"         "US"
"6"     "james-hetfield"    "1"         "US"
"7"     "abba"              "1"         "US"
"8"     "metallica"         "4"         "SE"
"9"     "abba"              "4"         "SE"

我正在使用此查询,但我失败了。我做错了什么,我该怎么做呢?

select distinct tagName a, sum(tagTotal) b from tags where tagCountryCode = 'US' order by b desc limit 20;

"a"         "b"
"metallica" "15"

我正试图获得如下结果:

metallica      7
abba           7
james-hetfield 1

1 个答案:

答案 0 :(得分:2)

您需要group by,而不是distinct

select tagName, sum(tagTotal) as cnt
from tags
where tagCountryCode = 'US'
group by tagName
order by cnt desc
limit 20;

我将别名更改为比ab更有意义的内容,但如果您愿意,可以保留这些别名。