选择最新而不是独特

时间:2016-07-11 00:54:15

标签: sql sql-server

目前我有一个存储过程,它从一个从API填充的数据库表中返回数据。当前查询是:

Select * 
From Inventory 
where StockNumber in (select distinct stocknumber)
order by Make

取而代之的是,我实际上需要根据DateTimeStamp列获取前1个最新记录,因为通常有许多记录具有相同的库存编号但时间戳不同。

2 个答案:

答案 0 :(得分:1)

一种方法是使用相关子查询:

Select i.*
From Inventory i
where i.datetime in (select max(i2.datetime)
                     from Inventory i2
                     where i2.stocknumber = i.stocknumber
                    )
order by i.Make;

另一种方法是使用ANSI标准窗口函数row_number()

select i.*
from (select i.*,
             row_number() over (partition by stocknumber order by datetime desc) as seqnum
      from Inventory i
     ) i
where seqnum = 1;

答案 1 :(得分:0)

使用INNER JOIN子句:

Select t1.* From Inventory t1 
INNER JOIN (SELECT StockNumber, MAX(Make) AS Make FROM Inventory GROUP BY StockNumber) t2
ON t1.StockNumber = t2.StockNumber AND t1.Make = t2.Make