Skip to content
Advertisement

Count entries by ranges?

I have a table like so:

deposits:
userId | amount
1      | 10
1      | 20
3      | 10
4      | 10

I need query which returns this:

count | amount
2     | 10      // id 3 and 4
1     | 30       // id 1

Count of users with this sum of amounts(balance)

Advertisement

Answer

You have to aggregate twice. The first time to SUM amount for each user. The second time to count the number of users for each amount.

select count(*), amount
from
(
    select userId, sum(amount) amount
    from deposits
    group by userId
) dt
group by amount
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement