简体   繁体   中英

Stuck with selecting distinct records with sum

Sorry guys, I tried, but I had to ask. I wasn't going anywhere with this.

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"

From this, I'm trying to select distinct parent , sum votes where type = 10 and country = 'us'

I tried this: SELECT SUM(likes.votes) FROM (SELECT DISTINCT parent, votes FROM likes where type = 10) likes; but I end up with pretty odd results.

How can I do this?

The result I'm trying to get is this:

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

check SQL fiddle

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

??

Try like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM