求一统计的SQL语句,急啊
表结构是这样的:
表名:tbl1
portbid, Cscid
表内容示例
protbid cscid
1 282
2 282
null 282
null 282
计算比例就是用portbid不为空的记录数除以cscid相同的记录总数,上例的比例计算出来就是50%
现在要写一个SQL语句,把所有比例为50%的cscid都取出来,请教高手这句SQL该如何写呢?
谢谢啊!
问题点数:100、回复次数:9Top
1 楼libin_ftsafe(子陌红尘:TS for Banking Card)回复于 2006-03-16 12:44:44 得分 10
select
distinct a.Cscid
from
tbl1 a
where
(select count(*) from tbl1 where Cscid=a.Cscid and portbid is not null)=
(select count(*) from tbl1 where Cscid=a.Cscid and portbid is null)Top
2 楼samson_www(天天向上)回复于 2006-03-16 12:54:51 得分 10
select cscid,count(cscid),count(porbid) from tb group by cscid having count(cscid)/count(porbid)=0.5Top
3 楼tntzbzc(华裔大魔王—抗日要从娃娃抓起)回复于 2006-03-16 13:04:01 得分 30
select cscid from
(select convert(float,count(protbid))/count(cscid) x ,cscid
from tbl1
group by cscid) a where a.x=0.5
如果protbid是INT 型,那就不必判断其是否是NULL值
count取值时不会把NULL值的protbid计算在内Top
4 楼sybaseengineer(萧何)回复于 2006-03-16 13:07:16 得分 10
select distinct cscid from tb group by cscid having count(cscid)/count(portbid)=0.5Top
5 楼tntzbzc(华裔大魔王—抗日要从娃娃抓起)回复于 2006-03-16 13:08:05 得分 0
select cscid from
(select convert(float,count(portbid ))/count(cscid) x ,cscid
from tbl1
group by cscid) a where a.x=0.5
如果protbid是INT 型,那就不必判断其是否是NULL值
count取值时不会把NULL值的protbid计算在内
Top
6 楼tomtown530(梦想一定会实现!)回复于 2006-03-16 13:15:48 得分 0
一楼大哥,这样可以获取比例为50%的,但是获取40%, 30%这样就不行了,不知道比例能不能保留一位小数?Top
7 楼zlp321002(Life Is Good,Let's Shine)回复于 2006-03-16 13:32:19 得分 40
--测试环境
Create table A(protbid int,cscid int)
insert into A select 1,282
union all select 2,282
union all select NULL,282
union all select NULL,282
union all select 4,285
union all select 6,285
union all select 7,283
union all select 8,283
union all select 9,283
--利用CTE
with A_CTE (cscid,COUNT1,COUNT2)
as
(
select cscid,
COUNT1=(SELECT count(*) from A where cscid=TB.cscid AND protbid is not null),
COUNT2=COUNT(DISTINCT cscid )
FROM A TB
group by cscid
)
SELECT cscid FROM A_CTE
WHERE CAST(CAST(COUNT2 AS float)/COUNT1 AS DECIMAL(4,2))=0.5 --0.4(40%)
--结果
/*
cscid
-----------
282
285
(2 行受影响)
*/
--删除测试环境
Drop table A
Top
8 楼aniude(重返荣耀)回复于 2006-03-16 14:31:01 得分 0
MarkTop
9 楼tomtown530(梦想一定会实现!)回复于 2006-03-17 14:32:08 得分 0
谢谢各位,深表感谢,:)现在结帖Top




