将SQL结果列切换到行并在下面包含摘要行

时间:2017-07-25 20:23:08

标签: sql tsql

我希望以下列填充在行的位置,然后在其下方包含摘要行:

table1
ID     NAME    Value   Group
001    Bob     100     A
002    Don     200     A
003    Fay     300     B

以下是所需输出的示例:

GROUP       NO    SUM    
Group A     2     300
Group B     1     300    
Total       3     600

2 个答案:

答案 0 :(得分:0)

Declare @YourTable Table ([ID] varchar(50),[NAME] varchar(50),[Value] int,[Group] varchar(50))
Insert Into @YourTable Values 
 ('001','Bob',100,'A')
,('002','Don',200,'A')
,('003','Fay',300,'B')

Select [Group] = IsNull('Group '+[Group],'Total')
      ,[No]    = count(*)
      ,[Sum]   = sum(Value)
 From @YourTable
 Group By rollup([Group])

返回

Group   No  Sum
Group A 2   300
Group B 1   300
Total   3   600

答案 1 :(得分:0)

select coalesce('Group '+ [group], 'Total') [Group], count([group]) No, sum(value) SUM
from table1
group by [group] with rollup

http://sqlfiddle.com/#!6/655f4/3