但是分组取的话就没辙了,求各位大神指点迷津~
declare @e_rq varchar(15),@orgid int;
select @e_rq='2015-07-31',@orgid=308;
select spbh,SUM(hsje) as hsje,ROW_NUMBER() over(order by sum(hsje) desc) as rowid
into #tb
from tb_asyy_zhfx_ygdc
where convert(varchar(7),execdate,120)= convert(varchar(7),@e_rq,120) and orgid=@orgid
group by spbh
-------------------取销售额80%的品种编号-------------------------
select spbh,hsje
into #A_spbh
from #tb a
where (select SUM(hsje) from #tb where rowid<=a.rowid)/(select SUM(hsje) from tb_asyy_zhfx_ygdc where convert(varchar(7),execdate,120)= convert(varchar(7),@e_rq,120) and orgid=@orgid)*100<80
tb_asyy_zhfx_ygdc :spbh 商品编号 hsje 销售额 dqfl 大区分类
1 个解决方案
#1
declare @e_rq varchar(15),@orgid int;
select @e_rq='2015-07-31',@orgid=308;
-- 求出各组总计
SELECT dqfl,
SUM(hsje) as hsje
into #ta
from tb_asyy_zhfx_ygdc
where convert(varchar(7),execdate,120)= convert(varchar(7),@e_rq,120)
and orgid=@orgid
group by dqfl
-- 求各组下面的商品统计
SELECT dqfl,
spbh,
SUM(hsje) as hsje,
ROW_NUMBER() over(PARTITION BY dqfl order by sum(hsje) desc) as rowid
into #tb
from tb_asyy_zhfx_ygdc
where convert(varchar(7),execdate,120)= convert(varchar(7),@e_rq,120)
and orgid=@orgid
group by dqfl, spbh
-- 每组的前80%
select b.dqfl,
b.spbh,
b.hsje
into #A_spbh
from #tb b
JOIN #ta a
ON a.dqfl = b.dqfl
where (select SUM(b1.hsje)
from #tb b1
where b1.dqfl = b.dqfl
AND b1.rowid <= b.rowid
) / a.hsje * 100 < 80
ORDER BY b.dqfl, b.rowid
#1
declare @e_rq varchar(15),@orgid int;
select @e_rq='2015-07-31',@orgid=308;
-- 求出各组总计
SELECT dqfl,
SUM(hsje) as hsje
into #ta
from tb_asyy_zhfx_ygdc
where convert(varchar(7),execdate,120)= convert(varchar(7),@e_rq,120)
and orgid=@orgid
group by dqfl
-- 求各组下面的商品统计
SELECT dqfl,
spbh,
SUM(hsje) as hsje,
ROW_NUMBER() over(PARTITION BY dqfl order by sum(hsje) desc) as rowid
into #tb
from tb_asyy_zhfx_ygdc
where convert(varchar(7),execdate,120)= convert(varchar(7),@e_rq,120)
and orgid=@orgid
group by dqfl, spbh
-- 每组的前80%
select b.dqfl,
b.spbh,
b.hsje
into #A_spbh
from #tb b
JOIN #ta a
ON a.dqfl = b.dqfl
where (select SUM(b1.hsje)
from #tb b1
where b1.dqfl = b.dqfl
AND b1.rowid <= b.rowid
) / a.hsje * 100 < 80
ORDER BY b.dqfl, b.rowid