如何将行分组到具有多个值的列中?
How can I group rows into columns with multiple values?
如何将未知数量的行分组为一行,其中设置的列决定分组?
我想转
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
select Group1, Group2, Group3, SUM(val1), SUM(val2), SUM(val3)
from tablename
GROUP BY Group1, Group2, Group3
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
您可以将 group by
子句与 sum
聚合函数一起使用,但要使其正常工作,您必须确保 val
列的数据类型为数字数据类型(int
、decimal
、smallint
等)
此外,sum
函数
将忽略任何 null
值
select Group1, Group2, Group3, sum(val1), sum(val2), sum(val3)
from <table_name>
group by Group1, Group2, Group3
您的查询本身就有您的答案。您想要对您的 gropunames 进行分组并对其他列执行 SUm。所有你需要做一个简单的查询
select sum(Val1 ),sum( Val2), sum( Val3) from table
group by Group1 , Group2, Group3
如何将未知数量的行分组为一行,其中设置的列决定分组?
我想转
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
select Group1, Group2, Group3, SUM(val1), SUM(val2), SUM(val3)
from tablename
GROUP BY Group1, Group2, Group3
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
您可以将 group by
子句与 sum
聚合函数一起使用,但要使其正常工作,您必须确保 val
列的数据类型为数字数据类型(int
、decimal
、smallint
等)
此外,sum
函数
null
值
select Group1, Group2, Group3, sum(val1), sum(val2), sum(val3)
from <table_name>
group by Group1, Group2, Group3
您的查询本身就有您的答案。您想要对您的 gropunames 进行分组并对其他列执行 SUm。所有你需要做一个简单的查询
select sum(Val1 ),sum( Val2), sum( Val3) from table
group by Group1 , Group2, Group3