简体   繁体   中英

Group records by UserID, select where on one column value and sum another

Using SQL in MySQLWorkbench I'd like to group records by 'UserID', select only the records that match where 'Weeks' are in(5,6,7,8) and sum the values for each user in 'Score'.

The records are actually stored in two tables that I am joining, a lineup table and lineup history table:

INNER JOIN vi_lineup on vi_lineup.lineup_master_id = vi_lineup_master.lineup_master_id

Obviously, I am a newbie. I did search SO first but did not find a matching question. I'll keep looking and hope someone answers here. Thanks for any help.

A comment asked about the Weeks. The game is based on a weekly model and we number them sequentially. Here's a working query joining the tables and selecting records based on the weeks:

select * FROM vi_lineup LU 
INNER JOIN vi_lineup_master LM 
WHERE (LU.week > 4 and LU.week < 9)  
AND LU.lineup_master_id = LM.lineup_master_id 
Limit 0,148000;

What I would like to do now is Group the records by LM.UserID and sum the values in LU.Score Thanks!

You have not told us where userid or score comes from. But assuming you can clarify that yourself, the "basic" structure of the query will be like this:

SELECT
      ??.UserID, SUM(??.score) AS sum_score
FROM vi_lineup lu
INNER JOIN vi_lineup_master lm ON lu.lineup_master_id = lm.lineup_master_id
WHERE lu.week between 5 and 8
GROUP BY
      ??.UserID

You will need to replace each ?? with the correct table alias "lu" or "lm"

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