坚持用总和选择不同的记录

时间:2013-05-09 04:48:25

标签: php mysql sql

对不起,伙计们,我试过,但我不得不问。我不会去任何地方。

Here's my table `likes`:
"id"    "type"  "parent" "country" "votes"
"1"          "1"    "0" "US"    NULL
"2"          "2"    "1" "US"    NULL
"3"          "3"    "2" "US"    NULL
"4"          "10"   "3" "US"    "5"
"5"          "10"   "3" "US"    "15"
"6"          "10"   "3" "US"    "25"
"7"          "3"    "2" "US"    NULL
"8"          "10"   "7" "US"    "40"
"9"          "10"   "7" "US"    "25"
"10"     "10"   "7" "US"    "60"
"19"     "3"    "1" "US"    NULL
"20"     "10"   "19"    "US"    "10"
"21"     "10"   "19"    "US"    "20"
"22"     "10"   "19"    "US"    "30"

由此,我正在尝试select distinct parent , sum votes where type = 10 and country = 'us'

我试过这个:SELECT SUM(likes.votes) FROM (SELECT DISTINCT parent, votes FROM likes where type = 10) likes;但我的结果非常奇怪。

我该怎么做?

我想要得到的结果是:

parent | total
3      | 45
7      | 125
9      | 60

3 个答案:

答案 0 :(得分:1)

检查SQL fiddle

select distinct parent, sum(votes) from likes 
where type = 10 and country = 'us' GROUP BY parent;

答案 1 :(得分:0)

select parent, sum(votes) ...
group by parent

...

答案 2 :(得分:0)

试试这个

SELECT parent,sum(votes) as total FROM `likes` 
WHERE type = 10 GROUP BY parent ORDER BY parent ASC