0

Here is an example of my table.

┌────────┬────────┬───────┐
│ UserId │ Status │ Value │
├────────┼────────┼───────┤
│ 1      │ 1      │ 10    │
│ 1      │ 0      │ 5     │
│ 2      │ 0      │ 8     │
│ 2      │ 1      │ 15    │
│ 1      │ 1      │ 10    │
│ 1      │ 0      │ 5     │
└────────┴────────┴───────┘

I need to GROUP BY rows with UserId then COUNT total rows in the group, to this point I have no problem but I also want to SUM(Value) according Status Column. Like COUNT my sql give me total sum of group rows but I need result like below :-)

┌────────┬──────────────────────┬─────────────────────┐
│ UserId │ SUM(Value) Status=1  │ SUM(Value) Status=0 │
├────────┼──────────────────────┼─────────────────────┤
│ 1      │        20            │        10           │
│ 2      │        15            │        8            │
└────────┴──────────────────────┴─────────────────────┘

NOTE: This type of query called Conditional Aggregation you may search for more about this.

1
  • 2
    It is called conditional aggregation. Commented Apr 29, 2022 at 10:37

2 Answers 2

1

use this

SELECT USERID,
SUM(CASE WHEN STATUS = 1 THEN VALUE ELSE 0 END ) AS ST1,
SUM(CASE WHEN STATUS = 0 THEN VALUE ELSE 0 END ) AS ST2 FROM 
DBO.TABLENAME
GROUP BY USERID
Sign up to request clarification or add additional context in comments.

4 Comments

you need to improve your query, what if more than two status code exist. you may use PIVOT
It's Dynamic if more then two states then add more case when you need just change column name. @MANthanNPatel if you agree then vat it.
@MANthanNPatel the question is tagged MySql and there is no PIVOT in MySql. Also Status is obviously a Boolean column.
Not mention bool, also tagged sql, anyways have a good day : )
1

Assuming that the data type of Status is BOOLEAN or INTEGER with only 0 and 1 as possible values:

SELECT UserId,
       SUM(Status * Value) Status_1,
       SUM((NOT Status) * Value) Status_0
FROM tablename
GROUP BY UserId;

See the demo.

4 Comments

this also works, but if status define in string then not work e.g. status = 'active' or something :-)
@Baisnabi This is an answer for the question that you posted and not any other question where status is string. Did you read my answer from the start: "Assuming that the data type of Status..."
My bad I upvoted you and I thing @PiyushKachhadiya answer first, so ...
@Baisnabi my comment has nothing to do with your voting. I responded to your comment which mentions that my query would not work if....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.