日期:2014-05-16  浏览次数:20937 次

请教sql分组查询
表1中有字段“余额”,如何按余额分成如下类别,并统计出合计额及其占百分比等,sql语句能实现吗?

账户余额分类         余额合计 余额占比 户数合计 户数占比
0元
0-0.1(含)万
0.1-1(含)万
1-10(含)万
10以上


------解决方案--------------------
select 账户余额分类,sum(余额) as 余额合计
from
(
SELECT 1 as 序号, '0元 ' as 账户余额分类, 余额 FROM 表1 where 余额=0
union all
SELECT 2 as 序号, '0-0.1(含)万 ' as 账户余额分类, 余额 FROM 表1 where 余额> 0 and 余额 <=1000
union all
SELECT 3 as 序号, '0.1-1(含)万 ' as 账户余额分类, 余额 FROM 表1 where 余额> 1000 and 余额 <=10000
union all
SELECT 4 as 序号, '1-10(含)万 ' as 账户余额分类, 余额 FROM 表1 where 余额> 10000 and 余额 <=100000
union all
SELECT 5 as 序号, '10以上 ' as 账户余额分类, 余额 FROM 表1 where 余额> 100000
) as t
group by 账户余额分类
order by min(序号)

------解决方案--------------------
SELECT 1 as 序号, '0元 ' as 账户余额分类, sum(余额) as 余额合计,count(*) as
户数合计,count(*)/(select count(*) from tt) as 户数占比,sum(余额)/(select sum(余额)
from tt) as 余额占比 FROM tt where 余额=0
union all
SELECT 2 as 序号, '0-0.1(含)万元 ' as 账户余额分类, sum(余额) as 余额合计,count(*) as
户数合计,count(*)/(select count(*) from tt) as 户数占比,sum(余额)/(select sum(余额)
from tt) as 余额占比 FROM tt where 余额 between 1 and 1000
union all
SELECT 3 as 序号, '0.1-1(含)万 ' as 账户余额分类, sum(余额) as 余额合计,count(*) as
户数合计,count(*)/(select count(*) from tt) as 户数占比,sum(余额)/(select sum(余额)
from tt) as 余额占比 FROM tt where 余额 between 1001 and 10000
union all
SELECT 4 as 序号, '1-10(含)万 ' as 账户余额分类, sum(余额) as 余额合计,count(*) as
户数合计,count(*)/(select count(*) from tt) as 户数占比,sum(余额)/(select sum(余额)
from tt) as 余额占比 FROM tt where 余额 between 10001 and 100000
union all
SELECT 5 as 序号, '10万以上 ' as 账户余额分类, sum(余额) as 余额合计,count(*) as
户数合计,count(*)/(select count(*) from tt) as 户数占比,sum(余额)/(select sum(余额)
from tt) as 余额占比 FROM tt where 余额> 100001
order by 序号