34,590
社区成员
发帖
与我相关
我的任务
分享
create table test
(
Payid varchar(10),
stdName varchar(10),
cash money,
pay money,
pay_count money
)
insert into test
select'3000001', '艾鹤' ,0.00, 125.00, 125.00
union all
select '3000002', '王艳辉', 0.00, 139.00 ,139.00
union all
select '3000003', '白阿乐', 0.00, 175.00,175.00
union all
select '3000004', '刘珊', 0.00, 175.00, 175.00
--方法一
select case grouping(Payid)
when 0 then Payid
when 1 then '总计'
end Payid,
stdName,
sum(cash) cash,
sum(pay) pay,
sum(pay_count) pay_count
from test
group by Payid,stdName
with rollup
having grouping(Payid)+grouping(stdName)in (0,2)
--方法二
select * from test
union all
select '总计', '', sum(cash) cash, sum(pay)pay, sum(pay_count) pay_count
from test
drop table test
如果数据量大的话建议你使用方法一因为一是系统执行的时候就已经分类汇总了,效率高点
以上个人意见
create table tb(Payid int, stdName varchar(50), cash decimal(18,2), pay decimal(18,2), pay_count decimal(18,2))
insert into tb select 3000001,'艾鹤',0.00,125.00,125.00
insert into tb select 3000001,'王艳辉',0.00,139.00,139.00
insert into tb select 3000001,'白阿乐',0.00,125.00,175.00
insert into tb select 3000001,'刘珊',0.00,175.00,175.00
--1
SELECT isnull(ltrim(payid),'合计') as payid,isnull(stdname,'') as stdname,
sum(cash) as cash,sum(pay) as pay,sum(pay_count) as pay_count
from tb group by payid, stdname
with ROLLUP
having grouping (Payid)+grouping (stdname) in(0,2)
--2
select ltrim(payid) as payid,stdname,cash,pay,pay_count from tb
union all
select '合计','',sum(cash) as cash,sum(pay) as pay,sum(pay_count) as pay_count from tb
SELECT * FROM T
UNION
SELECT '合计','',sum(cash),sum(pay),sum(pay_count)from T