我有以下查询,该查询根据用户来自网络还是移动用户来进行划分。我不仅要显示用户数,还要显示每个来源的总用户数百分比。如何在一个查询中计算?
select source, count(*) as total_users
from table
where is_active = 1
and source in ('web','mobile')
group by 1
答案 0 :(得分:2)
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
答案 1 :(得分:0)
尝试如下
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
答案 2 :(得分:0)
另一个演示文稿:
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
答案 3 :(得分:0)
我只是使用窗口函数来写这个:
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;