在同一sql表中用sum更新

czq61nw1  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(321)

我想根据项目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';
afdcj2ne

afdcj2ne1#

不确定数据库是什么,但如果是mssql server,则直接使用cte(公共表表达式):

;with cte_total
(
  select project_id, sum(column1) [c1total], sum(column2) [c2total], sum(column3) [c3total]
  from <YourTableName>
  where channel <> 'Total Channel'
  group by project_id
) 
update t
set column1 = c1Total, column2 = c2total, column3 = c3total
from <YourTableName> t
inner join cte_total ct ON (ct.project_id = t.project_id)
where t.chanel = 'Total Channel'

我已经从列名中删除了空格以使其更简单。
一个更简单的方法是按项目id求和,然后插入总行,而不是更新它们。

相关问题