在SQL中求和子查询

时间:2016-07-22 19:00:25

标签: mysql sql

所以此查询适用于特定的用户ID。

https://postimg.org/image/iq4jmvblj/

SELECT customer_profile.userID, 
    (SELECT sum(deposit.amountSuccessfulDeposits) 
        FROM customer_profile
        INNER JOIN deposit
            on deposit.userID = customer_profile.userID
        WHERE customer_profile.userID = 2022765) as depositSum,
    (SELECT sum(withdrawal.amountWithdrawal)
        FROM customer_profile
        INNER JOIN withdrawal
            on withdrawal.userID = customer_profile.userID
        WHERE customer_profile.userID = 2022765) as Wsum,
    customer_profile.amountGamingPlayerBalancecurrent as PlayerBalance,
    (sum(deposit.amountSuccessfulDeposits)*0.09) as Psum        

FROM customer_profile INNER JOIN存款     在deposit.userID = customer_profile.userID上 INNER JOIN退出     在withdraw.userID = customer_profile.userID上 WHERE customer_profile.userID = 2022765     AND withdraw.withdrawalType ='总计'

但是,当我运行整个数据仓库(相同的查询,但消除" customer_profile.userID = 2022765"行)时,它会为每个userID的depositSum值求和整个数据库,而不是计算每个用户ID的depositSum值。

我无法在子查询中使用该组,因为它会返回多个列。

https://postimg.org/image/3vfy8p20n/

    SELECT customer_profile.userID, 
        (SELECT sum(deposit.amountSuccessfulDeposits)
            FROM customer_profile
            INNER JOIN deposit
                    on deposit.userID = customer_profile.userID
            WHERE customer_profile.userID = deposit.userID) as depositSum,      
        (SELECT sum(withdrawal.amountWithdrawal)
            FROM customer_profile
            INNER JOIN withdrawal
                    on withdrawal.userID = customer_profile.userID
            WHERE customer_profile.userID = withdrawal.userID) as Wsum,
     customer_profile.amountGamingPlayerBalancecurrent as PlayerBalance,
        (sum(deposit.amountSuccessfulDeposits)*0.09) as Psum         
FROM customer_profile 
INNER JOIN deposit  on deposit.userID = customer_profile.userID 
INNER JOIN withdrawal   on withdrawal.userID = customer_profile.userID 
WHERE withdrawal.withdrawalType = 'Total' GROUP BY customer_profile.userID

帮助?

1 个答案:

答案 0 :(得分:0)

以下是使用correlated subqueries代替的一个选项:

select cp.userid,
       (select sum(amountsuccessfuldeposits)
        from deposit d
        where cp.userid = d.userid) as depositSum,
       (select sum(amountwithdrawal)
        from withdrawal w
        where withdrawaltype = 'Total' and cp.userid = w.userid) as wsum
from customer_profile cp
相关问题