首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

一张表,怎么求成功率

2012-03-13 
一张表,如何求成功率?表IDNAMEOK1张三成功2李四成功3张三失败4黎明成功5刘备成功6李四失败如何查出每个人

一张表,如何求成功率?


ID NAME OK  

1 张三 成功


2 李四 成功


3 张三 失败

4 黎明 成功

5 刘备 成功

6 李四 失败

如何查出每个人的成功率是多少? SQL语句。

[解决办法]

SQL code
select    name,    ltrim(sum(case ok when '成功' then 1 else 0 end)*100.0/count(1))+'%'from  tbgroup by  name
[解决办法]
SQL code
select    name,  成功率,  row_number()over(order by 成功率 desc) as ASfrom( select    name,    ltrim(sum(case ok when '成功' then 1 else 0 end)*100.0/count(1))+'%' as 成功率from  tbgroup 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
[解决办法]
SQL code
create table tb(id int,name nvarchar(20),ok nvarchar(4))goinsert tbselect 1,'张三','成功' union allselect 2,'李四','成功' union allselect 3,'张三','失败' union allselect 4,'黎明','成功' union allselect 5,'刘备','失败'goselect 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 行受影响)*/godrop table tb 

热点排行