Home > Mobile >  SQL Update based on grouping
SQL Update based on grouping

Time:01-09

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.

CodePudding user response:

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
  • Related