简体   繁体   中英

GROUP BY a CONCAT and another column SQL

I'm new here and pardon if I have any mistake. I tried a test question in my middle school and I'm not that good with SQL so I'm a bit confused. Any help is appreciated, thank you so much.

table CANDIDATES:

   ID FNAME LNAME
1  1  COCO  MELON
2  2  RED   SHANKS
3  3  OPTI  PRIME
4  4  BUGS  BUNNY

table VOTES:

   ID STATE
1  1  ALABAMA
2  1  ALABAMA
3  2  ALABAMA
4  3  TEXAS
5  4  TEXAS

The intended output is supposed to be like this:

    STATE   VOTES
1   ALABAMA COCO MELON x 2, RED SHANKS x 1
2   TEXAS   OPTI PRIME x 1, BUGS BUNNY x 1

I used CONCAT and I managed to group by the names. However, the states won't follow. It just don't want to group. Did I miss something? Thank you for your help. Here's the code that I did.

SELECT v.state, CONCAT(fname,' ',lname,' x ',COUNT(v.state))
FROM candidates c
INNER JOIN votes v ON v.id = c.id
GROUP BY v.state, c.fname, c.lname;

You can COUNT the votes before you JOIN the tables and use GROUP_CONCAT to join all names and counts together

SELECT v.state, GROUP_CONCAT(CONCAT(fname,' ',lname,' x ',v.count_) ORDER BY v.ID) FROM candidates c INNER JOIN (SELECT `ID`, `STATE`, COUNT(*) count_ FROM votes GROUP BY `ID`, `STATE`) v ON c.ID = v.ID GROUP BY v.state
state | GROUP_CONCAT(CONCAT(fname,' ',lname,' x ',v.count_) ORDER BY v.ID) 
:------ |  :----------------------------------------------------------------- 
ALABAMA | COCO MELON x 2,RED SHANKS x 1                                     
TEXAS | OPTI PRIME x 1,BUGS BUNNY x 1                                      

db<>fiddle here

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