我有两张有亲子关系的表
Table1
| Account_no | Main_account_no | bla bla
+------------+-----------------+----------
| 234 | 111 |
| 235 | 111 |
| 222 | 112 |
| 220 | 112 |
第二个:
Table2
| Account_no | Balance | bla bla
+------------+-----------------+----------
| 234 | 10 |
| 235 | 15 |
| 222 | 55 |
| 220 | 45 |
我需要的是计算每个父帐户的子帐户余额总和。 预期的结果是
| Main_account_no | Balance |
+-----------------+---------+
| 111 | 35 |
| 112 | 100 |
我正在尝试使用
SELECT MAIN_ACCOUNT_NO, SUM((SELECT BALANCE FROM TABLE2 WHERE ACCOUNT_NO = A.ACCOUNT_NO)) OVER (PARTITION BY MAIN_ACCOUNT_NO)
FROM TABLE1 A
GROUP BY MAIN_ACCOUNT_NO
但我得到了ORA-00979: not a GROUP BY expression
我哪里做错了?
答案 0 :(得分:2)
因为这显然不是家庭作业......: - )
首先让我们获取main_account_nos以及余额:
select
Table1.Main_account_no,
Table1.Account_no,
Table2.Balance
from
Table1
join Table2 on Table1.Account_no = Table2.Account_no
给出
| Main_account_no | Account_no | Balance |
+-----------------+------------+-----------------+
| 111 | 234 | 10 |
| 111 | 235 | 15 |
| 112 | 222 | 55 |
| 112 | 220 | 45 |
现在我们可以根据需要轻松分组:
select
Table1.Main_account_no,
sum(Table2.Balance) as total
from
Table1
join Table2 on Table1.Account_no = Table2.Account_no
group by
Table1.Main_account_no