想要在SQL Server

时间:2016-03-12 17:15:34

标签: sql sql-server

我有一张桌子A. 从A 中选择Field1,field2,我想在group bycount(field1)上执行group by field 2。但计数将是在同一个表上计算某些条件,如

Select (Count(All records) - count(Records which are Rejected)/Count(All records))*100 as [Rate] from A
Group by Field1,field2

结果应为

Field1 Count
A1      (calculation mentioned above)
B1      (calculation mentioned above)

2 个答案:

答案 0 :(得分:1)

我最喜欢的方法是使用带有条件表达式的AVG()

select field1,
       avg(case when status = 'Rejected' then 0.0 else 100.0 end) as Rate
from A
group by Field1;

但是,第一个条件是您决定拒绝某一行。另请注意,如果您希望在非聚合列中找到field1子句,则group by会进入。{/ p>

答案 1 :(得分:0)

我猜你需要这样的东西:

Select 
  Field1, 
  sum(case when status = 'R' then 0 else 1 end) / sum(1)*100.0 as [Rate] 
from A
Group by 
  Field1

这将计算没有'R'的行的百分比作为Field1的每个值的状态。

编辑:要使用整个表中的行数计算百分比,您可以使用变量:

declare @rows int

select @rows = count(*) from A 

Select 
  Field1, 
  (@rows - sum(case when status = 'R' then 1 else 0 end)) / @rows*100.0 as [Rate] 
from A
Group by 
  Field1