34,590
社区成员
发帖
与我相关
我的任务
分享
if object_id('tb','u') is not null
drop table tb
go
create table tb
(
sno varchar(10),
score int
)
go
insert into tb
select '001',60 union all
select '002',60 union all
select '003',70 union all
select '004',70 union all
select '005',100 union all
select '006',100 union all
select '007',100
go
declare @cnt int
select @cnt=count(*) from tb
select [60分所占比例]=(select count(*)*100/@cnt from tb where score=60),
[70分所占比例]=(select count(*)*100/@cnt from tb where score=70),
[100分所占比例]=(select count(*)*100/@cnt from tb where score=100)
/*
60分所占比例 70分所占比例 100分所占比例
----------- ----------- -----------
28 28 42
(1 行受影响)
*/
declare @tb table
(sno int,score int)
declare @i decimal(18,4),@sum decimal(18,4),@count decimal(18,4)
insert @tb (sno,score) select 001,100 union select 002 ,80 union select 003,60
select @i=count(*) from @tb where score>60
select @sum=count(*) from @tb
select @count=@i/@sum
select convert(varchar(20),@count*100)+'%'
declare @t table(sno int,score int);
insert into @t select 1,100 union all
select 2,98 union all
select 3,60 union all
select 4,65;
select score/10*10,COUNT(1)*1.0/(select COUNT(1) from @t) from @t group by score/10
----------------------------------------------------------------
-- Author :fredrickhu(小F,向高手学习)
-- Date :2011-11-03 09:13:21
-- Version:
-- Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (Intel X86)
-- Apr 22 2011 11:57:00
-- Copyright (c) Microsoft Corporation
-- Enterprise Evaluation Edition on Windows NT 6.1 <X64> (Build 7600: ) (WOW64)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([sno] varchar(3),[score] int)
insert [tb]
select '001',100 union all
select '002',80 union all
select '003',60
--------------开始查询--------------------------
select
ltrim(cast( sum(case score when 100 then 1 else 0 end)*100.0/(select count(1) from tb) as dec(18,2)))+'%' as [100分的百分比],
ltrim(cast( sum(case when score>=60 then 1 else 0 end)*100.0/(select count(1) from tb) as dec(18,2)))+'%' as [60分以上的百分比]
from
tb
----------------结果----------------------------
/* 100分的百分比 60分以上的百分比
------------------------------------------ ------------------------------------------
33.33% 100.00%
(1 行受影响)
*/
select (select count(*) from #tb where score>60)/(select count(*) from #tb)
select ltrim(cast( sum(case score when 100 then 1 else 0 end)*100.0/(select count(1) from tb) as dec(18,2)))+'%' from tb