I want to update SUM in same SQL table based on project id and Channel. for Total Channel= SUM(Channel 1 + Channel 2)
x
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
I am trying with below Query, but something is wrong in this query
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';
Advertisement
Answer
Not sure what your database is but if it is MSSQL Server then it is straight forward using CTE (Common Table Expression):
;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'
I have removed spaces from column names to make it easier.
An easier would be to sum up by project id and then insert total rows rather than updating them.