performance - 计算百分比的更快方法?

标签 performance tsql sql-server-2008-r2

我目前使用这种方法得出百分比:

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/

相关文章:

tsql - 简化的交叉连接?

sql-server-2008 - 自动重组和重建索引

SQL获取最新日期记录

c - strtok/strtok_r 中途退出解析

sql - 存储过程;插入缓慢

performance - 相对于 translateZ(0) 的 CSS 性能

sql - 仅对所有数据进行透视列更改

c# - 如何将数组传递给 SQL Server 存储过程

tsql - T-SQL 中的单行 IF

java - Array 和 ArrayList 位置访问性能