MySQL子查询仅返回顶行的结果

时间:2015-09-01 12:33:07

标签: mysql subquery

我无法解决如何做一些我确定非常简单的事情。我有以下代码:

SELECT SA.ACCOUNTHOLDERKEY
,SA.BALANCE
,`TOT`.TOTAL_BALANCE
,(SA.BALANCE/`TOT`.TOTAL_BALANCE)*100 AS PERCENT_OVER_FSCS_LIMIT

FROM savingsaccount SA
LEFT JOIN (SELECT
SUM(BALANCE) AS TOTAL_BALANCE
,ENCODEDKEY
FROM
savingsaccount
 ) AS `TOT` ON TOT.ENCODEDKEY= SA.ENCODEDKEY


where accountstate = 'ACTIVE'
GROUP BY SA.ACCOUNTHOLDERKEY

正如你所看到的,我试图弄清楚每个ACCOUNTHOLDERKEY的余额与所有余额的总和相差多少。但是,获取所有余额总和的子查询并不起作用,因为它只返回顶行的数字。我假设我的错误在连接逻辑中的某个地方?

2 个答案:

答案 0 :(得分:0)

所以我真的有一个完整的大脑放屁。我需要更多的睡眠!

我的查询的答案只是将子查询包含在select语句中:

SELECT SA.ACCOUNTHOLDERKEY
,(SELECT
sum(balance)
from
savingsaccount
WHERE
ACCOUNTSTATE = 'ACTIVE') AS TOTAL_DEPOSIT_BALANCE

FROM savingsaccount SA

where accountstate = 'ACTIVE'
GROUP BY SA.ACCOUNTHOLDERKEY

答案 1 :(得分:0)

您可以使用交叉联接: -

SELECT SA.ACCOUNTHOLDERKEY
        ,SA.BALANCE
        ,`TOT`.TOTAL_BALANCE
        ,(SA.BALANCE/`TOT`.TOTAL_BALANCE)*100 AS PERCENT_OVER_FSCS_LIMIT
FROM savingsaccount SA
CROSS JOIN 
(
    SELECT SUM(BALANCE) AS TOTAL_BALANCE
    FROM savingsaccount
) AS `TOT`
WHERE accountstate = 'ACTIVE'
GROUP BY SA.ACCOUNTHOLDERKEY

好像从主查询中有任何行返回时,子查询中总会有一行,然后这将有效。