简体   繁体   English

使用多列的最小日期时间更新临时表

[英]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"]?如何更新 #temp 表中的以下列“LowestFinishDate”以保存列 [“Finished_OldDate”、“Finished_NewDate”和“Current_FinishedDate”] 的绝对最小值?

This is what the table looks like for Parent0000:这是 Parent0000 的表格:

表结构

So in this case I want all 7 rows in #temp.[LowestFinishDate] for Parent0000 to be updated to the lowest date which is:因此,在这种情况下,我希望将 Parent0000 的 #temp.[LowestFinishDate] 中的所有 7 行更新为最低日期,即:

2020-11-25 14:15. 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.我尝试过 CROSS/OUTER APPLY 并使用表值构造函数,但由于某种原因,每个 LowestFinishDate 行都会使用 Current_FinishedDate 的对应值进行更新。

Thanks in advance提前致谢

In SQL Server, I would be inclined to write this as:在 SQL 服务器中,我倾向于将其写为:

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. cross apply取每行中日期的最小值。 The window function then takes the minimum across all rows for the parent id. window function 然后在所有行中为父 id 取最小值。

One method is use use MIN with a subquery and a VALUES table construct:一种方法是将MIN与子查询和VALUES表构造一起使用:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM