我有2个表(USERS和ACCOUNTS),其中包含以下数据:
用户
UserID Name Account_Number
10 John Smith 13
20 Alex Brown 14
30 Mary Wade 34
帐户
Account number Amount
13 40
34 30
14 30
13 60
14 10
我想知道如何编写查询以返回以下结果:
UserID Name Total amount
13 John Smith 100
14 Alex Brown 40
34 Mary Wade 30
我尝试的查询是:
SELECT USER_ID, NAME, (SELECT SUM(AMOUNT) FROM ACCOUNTS GROUP BY ACCOUNT) AS TOTAL_AMOUNT
FROM USERS
JOIN ACCOUNTS
USING(ACCOUNT_NUMBER)
ORDER BY TOTAL_AMOUNT DESC;
当我执行此操作时,我收到以下错误:ORA-01427:单行子查询返回多行。
是否有人知道我如何修改查询以使其按预期工作?
谢谢!
答案 0 :(得分:1)
删除子查询..它返回多行..
SELECT U.USERID, U.NAME, SUM(A.AMOUNT) AS TOTAL_AMOUNT
FROM USERS U
INNER JOIN ACCOUNT A on U.ACCOUNT_NUMBER=A.ACCOUNT_NUMBER
GROUP BY A.ACCOUNT_NUMBER,U.USERID, U.NAME
ORDER BY SUM(A.AMOUNT) DESC;
答案 1 :(得分:1)
也许是这样的:
SELECT
USERS.USER_ID,
USERS.NAME,
SUM(ACCOUNTS.Amount) AS TotalAmout
FROM USERS
JOIN ACCOUNTS
ON ACCOUNTS.Account_number=USERS.Account_number
GROUP BY
USERS.USER_ID,
USERS.NAME
ORDER BY
TotalAmout DESC
答案 2 :(得分:1)
请尝试:
select
Account_Number,
Name,
(select SUM(Amount) from ACOUNTS b where b.[Account number]=a.Account_Number) Total
from USERS a
order by Account_Number