日期:2014-05-17  浏览次数:20499 次

怎样在sqlserver2005中实现小计、合计
用存储过程或其他方式实现小计和合计的报表统计,提供思路也行,前台展示我用的是GridView,在后台代码或控件中操作也行,谢了
例:表table1
id orderNo standardTime amount productNo 
1 20090101 8 20 001
2 20090101 6 30 002
3 20090101 10 50 003
  .
  .
  .
4 20090102 8 50 004
5 20090102 12 30 005
6 20090102 10 10 006
  .
  .
  .
先分别统计orderNo 为20090101、20090102... 的standardTime*amount 的小计
然后统计所有orderNo 的standardTime*amount 德合计
如下:

id orderNo standardTime amount productNo perTotal
1 20090101 8 20 001 160
2 20090101 6 30 002 180
3 20090101 10 50 003 500
小计 840  
  .
  .
4 20090102 8 50 004 400
5 20090102 12 30 005 360
6 20090102 10 10 006 100
小计 860
  .
  .
  .

合计 1700

------解决方案--------------------
SQL code
create table #t(a int,b int,c int,d int,e int)  
insert into #t values(1,2,3,4,5)
insert into #t values(1,2,3,4,6)
insert into #t values(1,2,3,4,7)
insert into #t values(1,2,3,4,8)
insert into #t values(1,3,3,4,5)
insert into #t values(1,3,3,4,6)
insert into #t values(1,3,3,4,8)
insert into #t values(1,3,3,4,7)

insert into #t values(2,2,2,4,5)
insert into #t values(2,2,3,4,6)
insert into #t values(2,2,4,4,7)
insert into #t values(2,2,5,4,8)
insert into #t values(2,3,6,4,5)
insert into #t values(2,3,3,4,6)
insert into #t values(2,3,3,4,8)
insert into #t values(2,3,3,4,7)

select
case when grouping(a)=1 then '合计' else cast(a as varchar) end a, b, sum(c) as c,sum(d) as d,sum(e) as e
from
#t
group by
a,b
with rollup
having grouping(b)=0 or grouping(a)=1

select
case when grouping(a)=1 then '合计' else cast(a as varchar) end a, b, c, sum(d) as d,sum(e) as e
from
#t
group by
a,b,c
with rollup
having grouping(c)=0 or grouping(a)=1

select
case when grouping(a)=1 then '合计' else cast(a as varchar) end a, b,
case when grouping(c)=1 and grouping(b)=0 then '小计' else cast(c as varchar) end c,
sum(d) as d,sum(e) as e
from
#t
group by
a,b,c
with rollup
having grouping(a)=1 or grouping(b)=0

select
case when grouping(a)=1 then '合计' else cast(a as varchar) end a,
case when grouping(b)=1 and grouping(a)=0 then '小计' else cast(b as varchar) end b, sum(c) as c, sum(d) as d,sum(e) as e from #t
group by
a,b,c
with rollup
having grouping(a)=1 or grouping(b)=1 or grouping(c)=0

drop table #t

/*a                b      c      d      e     
------------------------------ ----------- ----------- ----------- -----------
1                2      12      16      26
1                3      12      16      26
2              &nb