简体   繁体   中英

sql query SUM IF GROUP BY

This is my table expense:

id2 name exp date ...
1  Jack 2
2  Joe  3.1
3  Marian 5.8
1  Jack  2
1  Jack  4
3  Marian 3

I want this query: sum up all person expenses and if the expenses was more than 5 echo it.

I have a problem on if section (if more than 5). I grouped by id2 and SUM(exp) and works fine but I don't know how to imply IF. I wrote SUM(IF(exp >= 5, 1, 0)) but sql error says is not correct group function.

S`ELECT id2, SUM(IF(exp >= 5, 1, 0)) as ex FROM expense GROUP BY id2`

I appreciate if you can help me with the query. Thanks

It is possible that this is what you want:

SELECT id2, SUM(exp),
       GROUP_CONCAT(CASE WHEN exp > 5 THEN exp END) as ExpsGreaterThan5
FROM expense
GROUP BY id2;
select id2,name,sum(exp) from expense group by user_id having sum(exp)>5

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