简体   繁体   中英

Update temp table with min datetime of multiple columns

How can I update the following column "LowestFinishDate" in my #temp table to hold the absolute mininium value of columns ["Finished_OldDate", "Finished_NewDate" and "Current_FinishedDate"]?

This is what the table looks like for Parent0000:

表结构

So in this case I want all 7 rows in #temp.[LowestFinishDate] for Parent0000 to be updated to the lowest date which is:

2020-11-25 14:15.

I have tried doing a CROSS/OUTER APPLY and use a table-value constructor but for some reason each LowestFinishDate rows gets updated with the correspondent value of Current_FinishedDate.

Thanks in advance

In SQL Server, I would be inclined to write this as:

with toupdate as (
      select t.*,
             min(least_date) over (partition by t.parentid) as new_lowestfinishdate
      from #temp t cross apply
           (select min(dte) as least_date
            from (values (t.Finished_OldDate),
                         (t.Finished_NewDate)
                         (t.Current_FinishedDate)
                 ) v(dte)
           ) v
     )
update toudpate
    set lowestfinishdate = new_lowestfinishdate;

The cross apply takes the minimum value of the dates within each row. The window function then takes the minimum across all rows for the parent id.

One method is use use MIN with a subquery and a VALUES table construct:

UPDATE YT
SET LowestFinishedDate = (SELECT MIN(V.FinishDate)
                          FROM (VALUES (YT.FinishedOldDate),
                                       (YT.FinishedNewDate),
                                       (YT.CurrentFinishDate)) V(FinishDate)
                          WHERE V.FinishDate IS NOT NULL)
FROM dbo.YourTable;

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