没有联合的表的金额总和

时间:2017-05-05 09:18:05

标签: sql sql-server sql-server-2008 tsql

我已经问了一个问题,我怎么能在不使用任何工会的情况下获得该专栏的总数。对此我有任何帮助。我尝试了很少的案例,但他们没有工作。任何帮助都会不胜感激。

样本表:

select * into #tab from (

    select 1 as id,10 amount
    union all
    select 2,20
    union all
    select 3,40 
    )as a
    select * from #tab

从下面查询我得到了结果,但在这里我不应该使用union all

 select  convert(varchar(250),id) as Ids ,amount from #tab
   union all
  select 'Total' as Total,Sum(Amount)as Final_Amount from #tab

我要求的输出:

    Ids amount
    1   10
    2   20
    3   40
  Total 70

4 个答案:

答案 0 :(得分:2)

你可以通过ROLLUP实现它

select  case when GROUPING(id) = 1 then 'Total' else convert(varchar(250),id) end as Ids 
        ,sum(amount)    as  amount
from #tab
group by id WITH ROLLUP 

答案 1 :(得分:2)

grouping sets

select CASE WHEN id IS NULL THEN 'Total' ELSE CAST(ID AS VARCHAR(MAX)) END AS id, sum(amount) 
from #tab 
group by grouping sets(id, ())

答案 2 :(得分:1)

我也试过ROLLUP

Select isnull(id,'Total') id,amount from    
    (
    select distinct cast(id as varchar)id,sum(amount) amount
     from #tab
    group by id with rollup
    )t4
    order by id

答案 3 :(得分:1)

这一个..将总数插入其自身(#tab)。

    IF OBJECT_ID('tempdb..#tab') IS NOT NULL
    BEGIN
        DROP TABLE #tab
    END

     /*============
       Sample table: 
      =============*/

    SELECT  *
    INTO    #tab
    FROM    ( SELECT    1 AS id ,
                        10 amount
              UNION ALL
              SELECT    2 ,
                        20
              UNION ALL
              SELECT    3 ,
                        40
            ) AS a

           /*=== END ==*/


            INSERT  INTO #tab
                    SELECT  0 id ,
                            SUM(amount) amount
                    FROM    #tab

            SELECT  CASE WHEN id = 0 THEN 'TOTAL'
                         ELSE CONVERT(VARCHAR(250), id)
                    END id ,
                    amount
            FROM    #tab

结果:

    id     amount
    ----   ----------
    1      10
    2      20
    3      40
    TOTAL  70

    (4 row(s) affected)