日期:2014-05-18 浏览次数:20515 次
--> --> (Roy)生成測試數據 if not object_id('Tempdb..#') is null drop table # Go Create table #([name] nvarchar(2),[status] nvarchar(4)) Insert # select N'A1',N'Pass' union all select N'A2',N'Fail' union all select N'A3',N'Pass' union all select N'A2',N'Pass' union all select N'A2',N'Pass' union all select N'A4',N'Pass' union all select N'A5',N'Pass' union all select N'A2',N'Fail' union all select N'A5',N'Pass' union all select N'A6',N'Pass' union all select N'A2',N'Fail' Go Select [name],StatusTime=COUNT(1), Pass=sum(case when [status]=N'Pass' then 1 else 0 end) ,[Pass-Ratio]=str(sum(case when [status]=N'Pass' then 1 else 0 end)*100.0/COUNT(1),6,2)+'%' from # group by [name] /* name StatusTime Pass Pass-Ratio A1 1 1 100.00% A2 5 2 40.00% A3 1 1 100.00% A4 1 1 100.00% A5 2 2 100.00% A6 1 1 100.00% */
------解决方案--------------------
SELECT name,COUNT(*) as statusTime,SUM(case when status='pass' then 1 else 0 end) as pass, CONVERT(varchar, CONVERT(float,SUM(case when status='pass' then 1 else 0 end))/COUNT(*)*100)+'%' as PassRatio FROM A GROUP BY name