表#t有数据如下:
a1      a2      amount
张三   现金     1000
李四   现金     2000
张三   购物卡   500
李四   代金券   300
我想这个表的数据如下:
a1          a2      amount
张三       现金     1000
张三       购物卡   500
小计                1500
李四       现金     2000
李四       代金券   300
小计                2300
总计                3800 这个sql语句如何写?

解决方案 »

  1.   

    create table t(a1 varchar(8), a2 varchar(8), amount int)
    insert t
    select '张三','现金', 1000 union all
    select '李四','现金', 2000 union all
    select '张三','购物卡', 500 union all
    select '李四','代金券', 300select isnull(a1,'总计')a1,isnull(a2,'小计')a2,max(amount)amount from t group by a1,a2 with rollup
    a1       a2       amount      
    -------- -------- ----------- 
    李四       代金券      300
    李四       现金       2000
    李四       小计       2000
    张三       购物卡      500
    张三       现金       1000
    张三       小计       1000
    总计       小计       2000
      

  2.   

    create table t(a1 varchar(8), a2 varchar(8), amount int)
    insert t
    select '张三','现金', 1000 union all
    select '李四','现金', 2000 union all
    select '张三','购物卡', 500 union all
    select '李四','代金券', 300select isnull(a1,'总计')a1,isnull(a2,'小计')a2,sum(amount)amount from t group by a1,a2 with rollup 
    a1       a2       amount      
    -------- -------- ----------- 
    李四       代金券      300
    李四       现金       2000
    李四       小计       2300
    张三       购物卡      500
    张三       现金       1000
    张三       小计       1500
    总计       小计       3800
      

  3.   

    create table t(a1 varchar(8), a2 varchar(8), amount int)
    insert t
    select '张三','现金', 1000 union all
    select '李四','现金', 2000 union all
    select '张三','购物卡', 500 union all
    select '李四','代金券', 300select (case when a2 is null and a1 is not null then '小计' else isnull(a1,'总计') end)a1,
            a2,sum(amount)amount from t group by a1,a2 with rollup 
    a1       a2       amount      
    -------- -------- ----------- 
    李四       代金券      300
    李四       现金       2000
    小计       NULL     2300
    张三       购物卡      500
    张三       现金       1000
    小计       NULL     1500
    总计       NULL     3800