现在有一张表,记录为:
ID1 JE FY1 FY2
01  10 20  30
01  20 20  40
02  10 10  50
02  20 30  50
02  20 50  50
现在要求得到如下结果:
ID1   JE   FY1  FY2
01    10   20   30
01    20   20   40
小计  30   40   70
02    10   10   50
02    20   30   50
02    20   50   50
小计  50   90   150
合计  80   130  220
即要明细与汇总 

解决方案 »

  1.   

    将所有记录及统计的记录插入临时表,再SELECT出来
      

  2.   

    用union也可以实现:
    select ID1, JE, FY1, FY2 from table where id1='01'
    union all
    select '小计', sum(JE), sum(FY1), sum(FY2) from table where id1='01'
    union all
    select ID1, JE, FY1, FY2 from table where id1='02'
    union all
    select '小计', sum(JE), sum(FY1), sum(FY2) from table where id1='02'
      

  3.   

    union不太现实吧`~~如果ID1有几百几千条不是要写几百几千个union?
      

  4.   

    --建立测试环境
    Create Table 表(ID1 varchar(10),JE varchar(10),FY1 varchar(10),FY2 varchar(10))
    --插入数据
    insert into 表
    select '01','10','20','30' union
    select '01','20','20','40' union
    select '02','10','10','50' union
    select '02','20','30','50' union
    select '02','20','50','50'
    select * from 表
    --测试语句
    --以下ord用于排序
     
    select ID1 as ord ,ID1, JE, FY1, FY2 from 表 
    union
    select ID1 as ord, '小计'  , sum(cast(JE as int)), sum(cast(FY1 as int)), sum(cast(FY2 as int)) from 表 group by  id1
    union
    select '总计' as ord, '总计'  , sum(cast(JE as int)), sum(cast(FY1 as int)), sum(cast(FY2 as int)) from 表 
    order by ord 
    --测试结果
    ord        ID1        JE          FY1         FY2         
    ---------- ---------- ----------- ----------- ----------- 
    01         01         10          20          30
    01         01         20          20          40
    01         小计         30          40          70
    02         02         10          10          50
    02         02         20          30          50
    02         02         20          50          50
    02         小计         50          90          150
    总计         总计         80          130         220
    --删除测试环境
    --Drop Table 表
      

  5.   

    先队表按ID1排序,建立一个临时表,循环插入记录,当ID1<>ID1.next时,插入sum求和的字段,循环是表结束sum整个表,小计字段也可以用变量存储 i:=0; i=i+当前插入字段的值,当ID1<>ID1.next时,插入i,i=0,然后重复以上操作
      

  6.   

    楼主试试我的语句呀~~~只要前台不要显示ord 字段就行了`~select ID1 as ord ,ID1, JE, FY1, FY2 from 表 
    union
    select ID1 as ord, '小计'  , sum(cast(JE as int)), sum(cast(FY1 as int)), sum(cast(FY2 as int)) from 表 group by  id1
    union
    select '总计' as ord, '总计'  , sum(cast(JE as int)), sum(cast(FY1 as int)), sum(cast(FY2 as int)) from 表 
    order by ord