使用表列值之一创建额外的总和列

时间:2018-11-15 17:50:51

标签: sql sql-server tsql

我有一个这样的表格数据:

Product     Value
A           20 
A           30
B           10
A           20
C           15
C           15

我需要根据Value列获取总和,例如:

Product     Value     Sum
A           20         70
A           30         70
B           10         10
A           20         70
C           15         30
C           15         30

如何查询以创建仍显示所有记录的所有A,B和C乘积之和?

3 个答案:

答案 0 :(得分:4)

您可以使用窗口函数求和:

create table #totalValue
(
[Product] varchar(55),
Value int
)

insert into #totalValue
values
('A',20), 
('A',30),
('B',10),
('A',20),
('C',15),
('C',15)


select 
    Product,
    [Value],
    sum([Value]) over (partition by Product) as [Sum]
from #totalValue

这应该比两次查询同一张表的解决方案更好。

答案 1 :(得分:3)

请尝试使用以下代码段。

select a.product, a.value, b.totalsum
from producttable as a
left join ( select sum(c.value) as totalsum,c.product 
            from producttable as c 
            group by c.product
           ) as b
on a.product = b.product

答案 2 :(得分:3)

你在这里

CREATE TABLE T(
  Product VARCHAR(20),
  Value INT
);

INSERT INTO T VALUES
('A', 20), 
('A', 30),
('B', 10),
('A', 20),
('C', 15),
('C', 15);

SELECT *, (SELECT SUM(Value) FROM T WHERE Product = T1.Product) [Sum]
FROM T T1;

返回:

+---------+-------+-----+
| Product | Value | Sum |
+---------+-------+-----+
| A       |    20 |  70 |
| A       |    30 |  70 |
| B       |    10 |  10 |
| A       |    20 |  70 |
| C       |    15 |  30 |
| C       |    15 |  30 |
+---------+-------+-----+