简体   繁体   中英

SQL Update based on grouping

Our system creates 2 lines per journal number and stamps a segment on each line.

Line 1 is system generated and line 2 is what the user has entered front end.

The issue is the 2nd line of each journal the system populates the segment in the way the user entered it front end, where as the 1st line populates the segment how its stored in the back end - this means we can have case sensitive issues across the journal itself. Not an issue on the journal but causes issues further down the line.

Currently the table looks like below

HMY Journal # Segment
1 10001 House
2 10001 HouSE
3 10002 FLAT
4 10002 flat
5 10003 Unit
6 10003 UniT

The 2nd lines segment of each journal must be updated to match the segment on the 1st line.

Desired end result:

HMY Journal # Segment
1 10001 House
2 10001 House
3 10002 FLAT
4 10002 FLAT
5 10003 Unit
6 10003 Unit

It has to update to how the system populated the segment so if it shows as all capitals, the 2nd line must be all capitals etc.

I have tried various methods but nothing is quite working how I would expect it. For example I was trying to find the min(hmy) grouped by journal number and update the segment of the max(hmy) grouped by journal number but it wouldn't.

Also looked at updating value based on previous row but could not work how I can incorporate that code into my issue.

You can use LAG to get previous value and update:


update  t
set Segment = PrevSegment
FROM    (
    select  *
    ,   LAG(Segment) OVER(PARTITION BY [Journal #] ORDER BY HMY) AS prevSegment
    FROM    journaltable j
    ) t
WHERE   prevSegment IS NOT NULL -- prevents writing the system generated value

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