日期:2014-05-17 浏览次数:20543 次
select team,
ok_num=sum(case when score='OK' then 1 else 0 end),
ng_num=sum(case when score='NG' then 1 else 0 end),
ok_rate=sum(case when score='OK' then 1 else 0 end)/count(1)*100.0
from [tb]
group by team
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-05-14 13:10:24
-- Version:
-- Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64)
-- Jun 17 2011 00:54:03
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1, v.721)
--
----------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([ID] varchar(3),[SCORE] varchar(2),[TEAM] varchar(1))
insert [huang]
select '001','OK','A' union all
select '002','NG','A' union all
select '003','OK','A' union all
select '004','OK','B' union all
select '005','NG','B'
--------------开始查询--------------------------
select [team], OK_NUM =SUM(CASE WHEN [team] =[team] AND score='OK' THEN 1 ELSE 0 END ),
NG_NUM =SUM(CASE WHEN [team] =[team] AND score='NG ' THEN 1 ELSE 0 END ),
OK_RATE=CONVERT(CHAR(5),CONVERT(DECIMAL(5,2),(SUM(CASE WHEN [team] =[team] AND score='OK' THEN 1 ELSE 0 END )*1.0/(SUM(CASE WHEN [team] =[team] AND score='OK' THEN 1 ELSE 0 END )+SUM(CASE WHEN [team] =[team] AND score='NG ' THEN 1 ELSE 0 END ))*100)))+'%'
from [huang]
GROUP BY [team]
---------------结果----------------------------
/*
team OK_NUM NG_NUM OK_RATE
---- ----------- ----------- -------
A 2 1 66.67%
B 1 1 50.00%
*/