如何将多个子查询与sum和group by进行整合

时间:2016-01-20 23:07:26

标签: mysql sql subquery

我需要用他们自己的“where and group by”限定符来显示用户信息和多个总和,这些限定符引用用户的交易余额。 我需要显示真实的余额,奖金余额和总余额。 用一笔钱来做这件事很简单,但我不能用多笔钱来做。

这是我对“真实余额”的查询:

 SELECT v2_user.id, v2_user.username, v2_user.first_name,
 v2_user.last_name,     coalesce(SUM(v2_wallet.amount),0) AS 'Real balance' 
 from v2_wallet
 join v2_user
 on v2_wallet.user_id = v2_user.id
 WHERE TYPE NOT LIKE '%BONUS%'
 group by v2_wallet.user_id

我想在我的查询中添加2个列:

SELECT COALESCE(SUM(v2_wallet.amount),0) AS 'bonus balance' from 
v2_wallet          
WHERE TYPE LIKE '%BONUS%' group by user_id

SELECT COALESCE(SUM(v2_wallet.amount),0) AS 'total balance' from v2_wallet group by user_id

2 个答案:

答案 0 :(得分:1)

我有一段时间没有做过MySql。但通常这个代码应该。这是使用SQL server sql语法测试的。

SELECT U.UserID,U.FirstName,T.TOTAL,B.BONUS 
FROM Users U 
LEFT JOIN (SELECT USERID, COALESCE (SUM(AMOUNT),0) AS TOTAL
            FROM WALLET
            GROUP BY USERID) AS T ON U.UserID=T.UserId
LEFT JOIN ( SELECT USERID, COALESCE (SUM(AMOUNT),0) AS BONUS
            FROM WALLET
            WHERE TYPE='BONUS'
            GROUP BY USERID) AS B ON U.USERID=B.USERID

答案 1 :(得分:0)

将条件嵌入SUM而不是WHERE子句中,依赖于布尔值为0或1的事实。

SELECT v2_user.id, v2_user.username, v2_user.first_name, v2_user.last_name,        
SUM(v2_wallet.amount*(TYPE not like '%BONUS%')) AS 'Real balance',
SUM(v2_wallet.amount*(TYPE like '%BONUS%')) AS 'Bonus balance',
SUM(v2_wallet.amount) AS 'Total balance'
from v2_wallet
join v2_user
on v2_wallet.user_id = v2_user.id
group by v2_wallet.user_id

如果v2_wallet.amount可能为NULL,则需要使用上面的COALESCE(v2_wallet.amount,0)。

如果你不喜欢它的外观,你可以使用IF代替乘法,比如

SELECT v2_user.id, v2_user.username, v2_user.first_name, v2_user.last_name,        
SUM(IF(TYPE not like '%BONUS%',v2_wallet.amount*,0)) AS 'Real balance',
SUM(IF(TYPE like '%BONUS%', v2_wallet.amount, 0)) AS 'Bonus balance',
SUM(v2_wallet.amount) AS 'Total balance'
from v2_wallet
join v2_user
on v2_wallet.user_id = v2_user.id
group by v2_wallet.user_id