我想根据项目id和通道更新同一个sql表中的sum。对于总通道=总和(通道1+通道2)
id | Channel | Project_id | Column1 | Column 2 | Column 3 |
-----------------------------------------------------------
1 Total Channel PR1 10 10 10
2 Channel 1 PR1 5 5 5
3 Channel 2 PR1 5 5 5
4 Total Channel PR2 20 40 30
5 Channel 1 PR2 10 20 15
6 Channel 2 PR2 10 20 15
7 Total Channel PR3 30 50 10
8 Channel 1 PR3 15 25 5
9 Channel 2 PR3 15 25 5
我正在尝试下面的查询,但此查询中有问题
UPDATE
results AS r
JOIN
( SELECT project_id,
SUM(Column1) AS sum_column1,
SUM(Column2) AS sum_column2,
SUM(Column3) AS sum_column3,
FROM results
WHERE channel <> 'Total Channel' and project_id=@project_id
GROUP BY project_id
) AS grp
ON
grp.project_id = r.project_id
SET
r.column1 = grp.sum_column1,
r.column2 = grp.sum_column2,
r.column3 = grp.sum_column3
WHERE
r.project_id = @project_id and r.channel='Total Channel';
1条答案
按热度按时间afdcj2ne1#
不确定数据库是什么,但如果是mssql server,则直接使用cte(公共表表达式):
我已经从列名中删除了空格以使其更简单。
一个更简单的方法是按项目id求和,然后插入总行,而不是更新它们。