Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.