日期:2014-05-18 浏览次数:20487 次
select name, ltrim(sum(case ok when '成功' then 1 else 0 end)*100.0/count(1))+'%' from tb group by name
------解决方案--------------------
select name, 成功率, row_number()over(order by 成功率 desc) as AS from ( select name, ltrim(sum(case ok when '成功' then 1 else 0 end)*100.0/count(1))+'%' as 成功率 from tb group by name )t
------解决方案--------------------
/*
表tbl
ID NAME OK
1 张三 成功
2 李四 成功
3 张三 失败
4 黎明 成功
5 刘备 成功
6 李四 失败
如何查出每个人的成功率是多少? SQL语句。
*/
go
if OBJECT_ID('tbl') is not null
drop table tbl
go
create table tbl(
id varchar(2),
name varchar(20),
ok varchar(4) check (ok in('成功','失败'))
)
go
insert tbl
select '1','张三','成功' union all
select '2','李四','成功' union all
select '3','张三','失败' union all
select '4','黎明','成功' union all
select '5','刘备','失败'
-------------------------------------------------------
select
name as 姓名,
left(成功率,charindex('.',CAST(成功率 as varchar))+2)+'%',
row_number()over(order by 成功率 desc) as 排名
from
(
select
name,
ltrim(sum(case ok when '成功' then 1 else 0 end)*100.0/count(1))+'%' as 成功率
from
tbl
group by
name
)t
------解决方案--------------------
create table tb(id int,name nvarchar(20),ok nvarchar(4)) go insert tb select 1,'张三','成功' union all select 2,'李四','成功' union all select 3,'张三','失败' union all select 4,'黎明','成功' union all select 5,'刘备','失败' go select name as 姓名,LTRIM(s)+'%' as 成功率,RANK()over(order by s desc)排名 from( select name,SUM(case when ok='成功' then 100 else 0 end)/COUNT(*)s from tb group by name )t /* 姓名 成功率 排名 -------------------- ------------- -------------------- 黎明 100% 1 李四 100% 1 张三 50% 3 刘备 0% 4 (4 行受影响) */ go drop table tb