我目前使用这种方法来提出一个百分比:
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
表被击中两次。
谢谢!
答案 0 :(得分:6)
这使您只能敲击一次表,并为给定的数据集提供相同的结果。
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
答案 1 :(得分:1)
以下是产生预期结果的替代查询。我不知道这个查询的性能与其他查询相比如何,但我怀疑你可以很容易地测试它。
declare @height table
(
UserId int,
tall bit
)
insert into @height
select 1, 1 union all
select 2, 1 union all
select 4, 1 union all
select 3, 0 union all
select 5, 0 union all
select 6, 0 union all
select 7, 0 union all
select 8, 0
Select 1.0 * Count(Distinct Case When Tall = 1 Then UserId End)
/ Count(Distinct UserId)
From @height