Reputation: 37
I have the following query that gives the split of our users based on if they came in from web or mobile. Instead of just the count of users, I want to show the percent of total users for each source. How would I calculate this in one query?
select source, count(*) as total_users
from table
where is_active = 1
and source in ('web','mobile')
group by 1
Upvotes: 0
Views: 46
Reputation: 1269833
I would just write this using window functions:
select source, count(*) as total_users,
count(*) / sum(count(*)) over () as ratio
from table
where is_active = 1 and
source in ('web', 'mobile')
group by source;
Upvotes: 0
Reputation: 74605
An alternative presentation:
SELECT
100.0*count(case when source = 'mobile' then 1 end) as mcount/count(*),
100.0*count(case when source = 'web' then 1 end) as wcount/count(*)
FROM
t
WHERE
source in ('web','mobile') and is_active = 1
Upvotes: 0
Reputation: 31993
try like below
with cte as
( select source, count(*) as total_users
from table
where is_active = 1
and source in ('web','mobile')
group by source
) SELECT source,total_users,
total_users * 100.0 / SUM(total_users) OVER () AS percentage from cte
Upvotes: 0
Reputation: 86715
SELECT
*,
total_users * 100.0 / SUM(total_users) OVER () AS percentage_of_total
FROM
(
select source, count(*) as total_users
from table
where is_active = 1
and source in ('web','mobile')
group by source
)
totals_by_source
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=6c0af52dcb10b072b876ae593773e148
Upvotes: 2