我目前使用这种方法得出百分比:
declare @height table
(
UserId int,
tall bit
)
insert into @height
select 1, 1 union all
select 2, 1 union all
select 6, 0 union all
select 3, 0 union all
select 7, 0 union all
select 4, 1 union all
select 8, 0 union all
select 5, 0
declare @all decimal(8,5)
select
@all = count(distinct UserId)
from @height
select
count(distinct UserId) / @all Pct
from @height
where tall = 1
结果:0.375000000
有没有更好的方法来做到这一点?如您所见,@height
table 被击中了两次。
谢谢!
最佳答案
这允许您只点击一次表格,并为您的给定数据集提供相同的结果。
declare @height table
(
UserId int,
tall bit
)
insert into @height
select 1, 1 union all
select 2, 1 union all
select 6, 0 union all
select 3, 0 union all
select 7, 0 union all
select 4, 1 union all
select 8, 0 union all
select 5, 0
select SUM(convert(decimal(8,5), tall)) / convert(decimal(8,5), COUNT(*)) Pct
from @height
根据您的要求,这可能适用于重复的用户 ID。至少它给出的结果与您的结果相同。
select SUM(convert(decimal(8,5), tall)) / convert(decimal(8,5), COUNT(distinct userid)) Pct
from
(select distinct UserId, tall
from @height) t
关于performance - 计算百分比的更快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5875692/