我的表格值低于
id name approved count
3 az 1 10
3 az 0 5
2 az 1 10
2 az 0 5
3 bz 1 10
3 bz 0 5
2 bz 1 10
2 bz 0 5
我需要用我的最终视图
计算已批准的%= 1id name Rate
3 az 66.66
3 bz 66.66
2 az 66.66
2 bz 66.66
如果费率为(10/15)* 100,即(已批准的数量= 1 /该ID,名称组合的总数)* 100
答案 0 :(得分:2)
这是使用条件聚合的一种方法
SELECT id,
NAME,
Isnull(Sum(CASE WHEN approved = 1 THEN [count] END) / Sum([count] * 1.0) * 100,0)
FROM your_table
GROUP BY id, NAME
* 1.0
用于避免整数除法
答案 1 :(得分:0)
select id,name,
sum(case when approved=1 then round(cast(count as float)/15*100,2) end) 'Rate'
from Your_Table
group by id,name
答案 2 :(得分:0)
如果您还想返回每行的详细信息。
create table #t(id int,name varchar(10),approved bit,count int)
insert into #t
select 3,'az',1,10 union all
select 3,'az',0,5 union all
select 2,'az',1,10 union all
select 2,'az',0,5 union all
select 3,'bz',1,10 union all
select 3,'bz',0,5 union all
select 2,'bz',1,10 union all
select 2,'bz',0,5
select * from (
select *,sum(case when approved=1 then count else 0 end )over()*1.0/sum(count)over() as perc from #t
) as t where t.approved=1 order by id desc
+----+------+----------+-------+----------------+ | id | name | approved | count | perc | +----+------+----------+-------+----------------+ | 3 | az | 1 | 10 | 0.666666666666 | | 3 | bz | 1 | 10 | 0.666666666666 | | 2 | bz | 1 | 10 | 0.666666666666 | | 2 | az | 1 | 10 | 0.666666666666 | +----+------+----------+-------+----------------+