根据 SQL Server 中的最新日期创建具有过滤值的新视图的最佳方法是啥?

Posted

技术标签:

【中文标题】根据 SQL Server 中的最新日期创建具有过滤值的新视图的最佳方法是啥?【英文标题】:What's the best way to create a new view with filtered values based on latest date in SQL Server?根据 SQL Server 中的最新日期创建具有过滤值的新视图的最佳方法是什么? 【发布时间】:2020-11-24 19:47:18 【问题描述】:

我有这样的看法:

我需要这样的新视图:

我知道我应该创建一个临时表,按 ProductID = 'abc' 的日期排序并选择临时表的第一行,创建一个新表,按 ProductID = 'def' 的日期排序并选择第一行新表并使用类似的东西

INSERT INTO mergedtable
   SELECT * FROM newtable
   UNION
   SELECT * FROM temptable

在所有产品 ID 的循环中。但是有没有更好的办法呢?

【问题讨论】:

请不要使用图像作为数据 - 使用格式化文本。 【参考方案1】:

您可以使用相关子查询:

select t.*
from t
where t.date = (select max(t2.date) from t t2 where t2.productid = t.productid);

【讨论】:

【参考方案2】:
select ID
, ProductID
, [Date]

from (
    select ID
    , ProductID
    , [Date]
    , max([Date]) over (partition by ProductID) as MaxDate

    from #product
) q

where [Date] = MaxDate

【讨论】:

以上是关于根据 SQL Server 中的最新日期创建具有过滤值的新视图的最佳方法是啥?的主要内容,如果未能解决你的问题,请参考以下文章