显示和列SQL代码

时间:2017-02-08 06:47:59

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

我需要使用SQL代码在col下显示sum col(item)吗?这是可能的

 Code            item                         
 ----            ----               
 1               30          
 3               40        
 4               50
 9               80
----             ----
Total            200

4 个答案:

答案 0 :(得分:2)

使用Rollup获取摘要行

SELECT CASE
         WHEN Grouping(code) = 1 THEN 'Total'
         ELSE Cast(code AS VARCHAR(50))
       END,
       Sum(item)
FROM   Yourtable
GROUP  BY code WITH rollup 

答案 1 :(得分:1)

select * from (select * from #Table1
union
select null, sum(item) item from #Table1)a
order by item 

答案 2 :(得分:1)

DECLARE @Table1  TABLE 
    (Code int, item int)
;

INSERT INTO @Table1
    (Code, item)
VALUES
    (1, 30),
    (3, 40),
    (4, 50),
    (9, 80)
;

脚本:

select Code , sum(item)item
 from @Table1
 group by GROUPING SETS((Code) , ())
 order by Code DESC

答案 3 :(得分:0)

Select
   Code,
   item 
from
   @ table_name 
Union All
select
   Null,
   sum(item)item 
from
   @ table_name

由于我们使用的联合如此明显,并且将保存按操作的顺序。