Jump to content

Help with SQL query with 3 WHERE / SUM statements


jp1989

Recommended Posts

Hi all. I am having trouble building my SQL query that attempts to get the SUM of all points for 3 types of activities - for each user. My query is below and here is an image that explains what I'm trying to do. I am quite close, and I kind of know what's going wrong, but would love some help! http://imgur.com/Lyjh7UD [1] (my problem and what I'd like).

 

Query:

SELECT *
FROM
(
SELECT userid, SUM(points) AS totalPoints FROM entries
WHERE competitionId = '$competitionId'
GROUP BY userid
)x, (

SELECT userid, activity_id, SUM(points) AS points1
FROM entries
WHERE competitionId = '$competitionId'
AND activity_id = '1'
GROUP BY activity_id
)a, (

SELECT userid, activity_id, SUM(points) AS points2
FROM entries
WHERE competitionId = '$competitionId'
AND activity_id = '2'
GROUP BY activity_id
)b, (

SELECT userid, activity_id, SUM(points) AS points3
FROM entries
WHERE competitionId = '$competitionId'
AND activity_id = '3'
GROUP BY activity_id
)c

Solved.
 
SELECT userid
, SUM(points) AS totalPoints
, SUM(CASE WHEN activity_id = 1
THEN points
ELSE NULL END) AS points1
, SUM(CASE WHEN activity_id = 2
THEN points
ELSE NULL END) AS points2
, SUM(CASE WHEN activity_id = 3
THEN points
ELSE NULL END) AS points3
FROM entries
WHERE competitionId = '$competitionId'
GROUP
BY userid

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.