简体   繁体   中英

Update each code with max value

I have a table that looks something like

CODE    NUMBER     MAX_NUMBER
1001    1          
1001    2  
1001    3  
1001    4 
1006    1 
1006    2 
1006    3
1008    1
1008    2 

I am looking for an update statement to set the max number for each code in the MAX_NUMBER field for every row. So for example the table should look like the following when update is complete

CODE    NUMBER     MAX_NUMBER
1001    1          4
1001    2          4
1001    3          4
1001    4          4
1006    1          3
1006    2          3 
1006    3          3
1008    1          2
1008    2          2

I know the following select

SELECT CODE, MAX(NUMBER) AS 'MAX'
FROM table
GROUP BY CODE

will give me

CODE      MAX
1001      4
1006      3
1008      2

Just need the update to put the max number in for every row

Thanks

Try this (MS-SQL Server)

UPDATE <table> SET max_number=xx.MAX
FROM 
(
    SELECT CODE, MAX(NUMBER) AS 'MAX'
    FROM <table>
    GROUP BY CODE
) xx
WHERE xx.code=<table>.code

A different approach would be to create a view and reference that instead of the actual table.

create view TableWithMax
as
select mm.code,mm.number,xx.max as max_number
from mm.table 
join ( 
    SELECT CODE, MAX(NUMBER) AS 'MAX'
    FROM table
    GROUP BY CODE) xx
on xx.code = mm.code

You will pay a bit of a performance hit, but your data will be accurate

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