当前位置: 代码迷 >> Sql Server >> 一张表,怎么求成功率
  详细解决方案

一张表,怎么求成功率

热度:6   发布时间:2016-04-27 14:56:58.0
一张表,如何求成功率?


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
  相关解决方案