我正在尝试对1列的值求和并将其仅按1列分组,但还要显示其他列。
基本上,如果数据看起来像这样:
Column1 Column2 Column3 Column4
----------------------------------
Col1Data0 Test1 Test2 1
Col1Data0 Test1 Test2 3
Col1Data1 Test1 Test2 2
Col1Data1 Test1 Test2 5
查询应输出:
Column1 Column2 Column3 Column4
Col1Data0 Test1 Test2 4
Col1Data0 Test1 Test2 4
Col1Data1 Test1 Test2 7
Col1Data1 Test1 Test2 7
答案 0 :(得分:5)
您可以使用SUM窗口功能:
测试数据:
declare @t table (Column1 varchar(10), Column2 varchar(10), Column3 varchar(10), Column4 int)
insert into @t values
('Col1Data0','Test1','Test2',1),
('Col1Data0','Test1','Test2',3),
('Col1Data1','Test1','Test2',2),
('Col1Data1','Test1','Test2',5)
查询:
SELECT Column1, Column2, Column3,
SUM(Column4) OVER (PARTITION BY Column1) AS SumColumn4
FROM @t
返回:
Column1 Column2 Column3 SumColumn4
Col1Data0 Test1 Test2 4
Col1Data0 Test1 Test2 4
Col1Data1 Test1 Test2 7
Col1Data1 Test1 Test2 7
答案 1 :(得分:1)
您可以使用子查询获取第1列的总和,并将其加入以获取输出
Select a.Column1,a.Column2,a.Column3,b.summ
FROM Table a
INNER JOIN (Select column1,sum(Column4) summ from Table group by column1) b
on b.column1 = a.column1
答案 2 :(得分:1)
使用标量子查询
select Column1,Column2,Column3,
(
select sum(Column4) from tablename b
where a.Column1=b.Column1 and a.Column2=b.Column2 and a.Column3=b.column3
) as column4
from tablename a