我有一张这样的表
+------------------------------+
| Name,Class,Value,Class_Total |
+------------------------------+
| John ,A ,10, 0 |
| Jake ,A ,22, 0 |
| Jill ,B ,34, 0 |
+------------------------------+
我想运行一个UPDATE查询,用每个类的总数填充Class_Total,结果将是
+------------------------------+
| Name,Class,Value,Class_Total |
+------------------------------+
| John ,A ,10, 32 |
| Jake ,A ,22, 32 |
| Jill ,B ,34, 34 |
+------------------------------+
目前我有这个
UPDATE dbo.Contrived
SET Class_Total = (SELECT SUM(Value)
FROM dbo.Contrived
)
但是这会将Class_Total中所有类的总数不仅仅是行所属的类,我需要以某种方式按类对项目进行分组。我知道我可以做一个
WHERE Class ='A'
在Select中,我想自动为很多课程做。 希望有意义,谢谢。
答案 0 :(得分:2)
您可以使用简单的子查询:
UPDATE c
SET c.Class_Total = (SELECT SUM(c2.Value)
FROM dbo.Contrived c2
WHERE c2.Class = c.Class)
FROM dbo.Contrived c
答案 1 :(得分:0)
请尝试使用CTE
:
;with T as(
select *, SUM(Value) over(partition by Class) sm
From dbo.Contrived
) update T set Class_Total=sm