如何将行分组为具有多个值的列?

时间:2015-04-17 08:48:04

标签: sql sql-server tsql grouping pivot-table

如何将未知数量的行分组到一行中,其中设置列确定分组?

我想转移

Group1   Group2   Group3    Val1   Val2   Val3
===============================================
John      Smith     25      1      0      0
John      Smith     25      0      6      0
John      Smith     25      0      0      8
Chris     Green     30      0      3      0
Chris     Green     30      5      0      0

Group1   Group2   Group3    Val1   Val2   Val3
===============================================
John      Smith     25      1      6      8
Chris     Green     30      5      3      0

4 个答案:

答案 0 :(得分:2)

declare @t table (group1 varchar(10),group2 varchar(20),group3 int,val1 int,val2 int,val3 int)

insert into @t (group1,group2,group3,val1,val2,val3)values ('John','Smith',25,1,0,0),
('John','Smith',25,1,6,0),
('John','Smith',25,1,0,8),
('Chris','Green',30,1,0,0),
('Chris','Green',30,1,3,0),
('Chris','Green',30,5,0,0)

select distinct group1,group2,group3,MAX(val1),MAX(val2),MAX(val3) from @t
group by group1,group2,group3 
ORDER BY group1 desc,group2 desc

答案 1 :(得分:1)

您可以将group by子句与sum聚合函数一起使用,但要使其正常工作,您必须确保val列的数据类型是数字数据类型(intdecimalsmallint等) 此外,null函数

将忽略任何sum
select Group1, Group2, Group3, sum(val1), sum(val2), sum(val3)
from <table_name>
group by Group1, Group2, Group3

答案 2 :(得分:1)

您的查询本身就有答案。你想分组你的gropunames并在其他列上执行SUm。所有你需要做一个简单的查询

select sum(Val1 ),sum( Val2), sum(  Val3) from table 
group by Group1 ,  Group2,   Group3    

http://www.w3schools.com/sql/sql_groupby.asp

答案 3 :(得分:0)

select Group1, Group2, Group3, SUM(val1), SUM(val2), SUM(val3)
from tablename
GROUP BY Group1, Group2, Group3