现在表中有数据:
id count times
1    10   15
2    17    23
这样形式的数据,现在想把count和times
这两个 字段的数据在最后一行形成一个总计,要怎么来实现?

解决方案 »

  1.   

    select * from tb
    union all
    select '合计',sum([count]) as [count],sum(times) as times from tb
      

  2.   

    ----------------------------------------------------------------
    -- Author  :fredrickhu(我是小F,向高手学习)
    -- Date    :2009-12-28 11:49:38
    -- Version:
    --      Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86) 
    -- Nov 24 2008 13:01:59 
    -- Copyright (c) 1988-2005 Microsoft Corporation
    -- Developer Edition on Windows NT 5.2 (Build 3790: Service Pack 1)
    --
    ----------------------------------------------------------------
    --> 测试数据:[tb]
    if object_id('[tb]') is not null drop table [tb]
    go 
    create table [tb]([id] int,[count] int,[times] int)
    insert [tb]
    select 1,10,15 union all
    select 2,17,23
    --------------开始查询--------------------------
    select ltrim(id) as id,[count],[times] from tb
    union all
    select '合计',sum([count]) as [count],sum(times) as times from tb
    ----------------结果----------------------------
    /* id           count       times
    ------------ ----------- -----------
    1            10          15
    2            17          23
    合计           27          38(3 行受影响)*/
      

  3.   

    select * from 表
    union all
    select '总计',sum([count]) ,sum(times) from 表
      

  4.   

    SELECT isnull(ltrim(id),'总计'),sum(COUNT) [count],sum(times) times 
    FROM @a GROUP BY id with rollup
      

  5.   

    select * from tb
    union all
    select '合计',sum([count]) as [count],sum(times) as times from tb