drop table #a
go
create table #a
(
A tinyint,
B char(4),
C smallint,
D tinyint
)
--插入数据
insert into #a (A,B,C,D)
values (1,'张三',100,10),
(2,'李四',200,20),
(3,'王武',300,30),
(4,'李逵',400,40)
--语句
with a as(
select cast(case grouping(A) when 0 then A else cast('合计' as sql_variant) end as char(4)) as A,cast(case grouping(A) when 0 then B else cast('合计' as sql_variant) end as char(4)) as B,sum(C) as C,sum(D) as D,row_number() over(partition by A order by A ) as rn
from #a
group by rollup(A,B)
)
select * from a where rn <>2 order by A
--结果展示
/*
A B C D rn
---- ---- ----------- ----------- --------------------
1 张三 100 10 1
2 李四 200 20 1
3 王武 300 30 1
4 李逵 400 40 1
合计 合计 1000 100 1
(5 行受影响)
*/
用 sum( A库存) over(paritition by a代码 ) 得到A的合计用 sum( B库存) over(paritition by b代码 ) 得到B的合计
同时这两个可以相加的。你试试
select sum(total) over() hj,* from (select er_bxzb.djbh as djbh,
er_djlx.djlxmc as djlxmc,
bd_costsubj.costname as costname,
bd_deptdoc.deptname as deptname,
bd_psndoc.psnname as psnname,
sum(er_bxzb.total) as total,
er_bxzb.djrq as djrq
from er_bxzb
inner join bd_costsubj
ON er_bxzb.szxmid = bd_costsubj.pk_costsubj
inner join bd_deptdoc
on er_bxzb.deptid = bd_deptdoc.pk_deptdoc
inner join bd_psndoc
on er_bxzb.jkbxr = bd_psndoc.pk_psndoc
inner join er_djlx
on er_bxzb.djlxbm = er_djlx.djlxbm
where er_bxzb.djlxbm in ('264X-0201', '264X-0202')
group by er_bxzb.djbh,
er_djlx.djlxmc,
bd_costsubj.costname,
bd_deptdoc.deptname,
bd_psndoc.psnname,
er_bxzb.djrq
) t
就是在你的语句外再包一层,加个sum() over()就可以了
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)