2014-11-14 33 views
0

我想選擇不同的tagName以及那些tagNames的總和,但似乎只得到一個結果。MySql選擇不同總合產量奇怪的結果

"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 

回答

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,但你可以保留這些,如果你喜歡。