【问题标题】: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 的循环中。但是有没有更好的办法呢?

【问题讨论】:

  • 请不要使用图像作为数据 - 使用格式化文本。

标签: sql sql-server


【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-15
      • 2013-02-26
      • 1970-01-01
      • 2011-06-30
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多