简体   繁体   中英

How to : update column with sum column in same table in SQL Server 2014?

Before table data:

-----------------------
|ID |WORK|VALUE|TOTAL|
-----------------------
|ID1|WRITE  |10 |   |
|ID1|TYPE   |5  |   |
|ID2|READ   |25 |   |
|ID2|SCAN   |30 |   |
|ID3|PRINT  |15 |   |
|ID4|SETTING|20 |   |
|ID5|REPAIR |5  |   |
|ID5|MAINTE |25 |   |
|ID5|MONITOR|20 |   |

Total is sum value from same id

ID1     10+5
ID2     25+30
ID3     15
ID4     20
ID5     50

For now I use the insert method with create table data2 (ID,TOTAL)

INSERT INTO DATA2(DATA2.ID, DATA2.TOTAL)
    SELECT DATA.ID, SUM (DATA.VALUE) AS TOTAL
    FROM DATA
    GROUP BY DATA.ID

Then I do SELECT JOIN FROM DATA2 AND DATA

After table data

-----------------------
|ID |WORK|VALUE|TOTAL|
-----------------------
|ID1|WRITE  |10 |15 |
|ID1|TYPE   |5  |15 |
|ID2|READ   |25 |55 |
|ID2|SCAN   |30 |55 |
|ID3|PRINT  |15 |15 |
|ID4|SETTING|20 |20 |
|ID5|REPAIR |5  |50 |
|ID5|MAINTE |25 |50 |
|ID5|MONITOR|20 |50 |

To update the value total to table, you need to have the column..

alter table tblname
add total int

If this is not a one time approach,i would recommend creating a view like below

create view somename
as
    select id,work,value,
    sum(value) over (partition by id ) as total
    from tabel

if you want to update table as one time excercise

;with cte
as
(select id,work,value,
sum(value) over (partition by id ) as total1
from tablename
)
update t
set t.total=c.total1
from cte c
join tablename t
on t.id=c.id

Another way to update the total.

UPDATE T1
SET T1.TOTAL=T2.TOTAL
FROM YOUT_TABLE T1
JOIN (
SELECT ID,SUM(VALUE) AS  TOTAL
FROM YOUR_TABLE 
GROUP BY ID
) T2 ON T1.ID=T2.ID

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM