首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQL中的求和子查询

SQL中的求和子查询
EN

Stack Overflow用户
提问于 2016-07-23 03:00:25
回答 1查看 96关注 0票数 0

因此,此查询适用于特定的userID。

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

代码语言:javascript
复制
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 deposit.userID = customer_profile.userID INNER JOIN deposit withdrawal.userID = customer_profile.userID WHERE customer_profile.userID = 2022765 AND withdrawal.withdrawalType = 'Total‘

但是,当我针对整个数据仓库运行时(相同的查询,但去掉了"customer_profile.userID = 2022765“行),它会对整个数据库中每个userID的depositSum值求和,而不是计算每个单独userID的depositSum值。

我不能在子查询中使用group by,因为它会返回多列。

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

代码语言:javascript
复制
    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

帮助?

EN

回答 1

Stack Overflow用户

发布于 2016-07-23 03:08:14

以下是改用correlated subqueries的一种选择:

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38533602

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档