简体   繁体   中英

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,

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? It just shows 1s in all the queries...

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

[Result][1]; [The E/R Diagram][2]

Thanks in advance:!! [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.

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. I updated your query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM