Tuesday, 15 May 2012

sql - How to update a row based on min/max values in related rows -


I tried to generate the title as much as possible, but in my mind it's a very typical example:

I have a table table in which my lines have a start date and end date. Each row will also be linked to an ID, for simplicity, assuming that every end date is currently zero.

I want to populate enddates with the following arguments:

The end date for the row X should be at least the beginning of all the other rows with the same ID as the row X More than the startup of the line X, it is going to start.

The only solution I have taken up so far is to include the row by row and by creating the update statement row from the row, which has awesome performance, I'm losing a bit on this one I like the following On some loops, I am using a floating table which I have interests (which are redundant end dates):

  Update BaseTable SET EffectiveEndDate = Min.Date Choose from Minimum (BaseTable.StartDate) as the date, temporarily temporarily in the form of Temporary Inner Joyein Base on BaseTable.id = Temp.Id, where temp.ro = @oo and baseTable.artdate & gt; Temporary. Temptible by StartData Group) where the BaseTable is the minimum. Id = minimum If you specify your RDBMS, SQL Server 2012 gives you the analytical functions of    

and lag . Based on your description, I think the following will work: according to the ID order from the table order by SELECT id, startdate, lag (startdate) over (according to the ID order, initially by DESC), initial DESC;

Edit:

That should be possible with earlier versions of SQL Server, but you As the lag function is new in SQL Server 2012, write some code to simulate.

No comments:

Post a Comment