[英]How to count the number of bank accounts that belong to one user in Oracle SQL
I've got a few questions regarding the use of GROUP BY in SQL,我有几个关于 SQL 中使用 GROUP BY 的问题,
How do you count the number of open bank accounts that belong to one specific user?您如何计算属于某个特定用户的开立银行账户数量? I tried to write the most correct sentence possible so that the SQL could count all the associated accounts of each user, instead the result is somewhat easy?
我试图写出最正确的句子,以便 SQL 可以计算每个用户的所有关联帐户,而不是结果有点容易? It just shows 1s in all the queries...
它只在所有查询中显示 1...
SELECT DISTINCT RPAD(CLI.NOMBRE || ' ' ||CLI.APELLIDOS,30) "Nombre y Apellidos",
SUM(CUE.SALDO) "Saldo", COUNT(CUE.COD_CUENTA) "Cuentas Abiertas"
from CLIENTE CLI,
CUENTA CUE
WHERE CLI.COD_CLIENTE = CUE.COD_CLIENTE
GROUP BY CLI.NOMBRE, CLI.APELLIDOS, CUE.SALDO, CUE.COD_CUENTA
In my case, I tried looking for users with name and surnames and also count the accounts that users have opened, instead, the query repeats names and the "Counter" shows 1s as result就我而言,我尝试查找具有姓名和姓氏的用户,并计算用户打开的帐户,相反,查询重复名称,“计数器”显示 1 作为结果
[Result][1]; [结果][1]; [The E/R Diagram][2]
[E/R 图][2]
Thanks in advance:!!提前致谢:!! [1]: https://i.stack.imgur.com/AQDac.png [2]: https://i.stack.imgur.com/jlVte.png
[1]: https://i.stack.imgur.com/AQDac.png [2]: https://i.stack.imgur.com/jlVte.png
You are grouping by SALDO
and COD_CUENTA
and that prevents traditional aggregation counts to show the result you want.您正在按
SALDO
和COD_CUENTA
进行分组,这会阻止传统的聚合计数显示您想要的结果。
However, you can use a window function: you need to tell the COUNT()
function about the scope it needs to operate adding OVER(PARTITION BY cli.cod_cliente)
. However, you can use a window function: you need to tell the
COUNT()
function about the scope it needs to operate adding OVER(PARTITION BY cli.cod_cliente)
.
For example:例如:
select distinct
rpad(cli.nombre || ' ' || cli.apellidos, 30) as "nombre y apellidos",
sum(cue.saldo) as "saldo",
count(cue.cod_cuenta) over(partition by cli.cod_cliente) as "cuentas abiertas"
from cliente cli
join cuenta cue on cli.cod_cliente = cue.cod_cliente
group by cli.nombre, cli.apellidos, cue.saldo, cue.cod_cuenta
NOTE : Please use modern join syntax, not those joins from the 80s.注意:请使用现代连接语法,而不是 80 年代的连接。 I updated your query.
我更新了你的查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.