SQL服务器查询显示最近的不同数据

问题描述 投票:0回答:2

我试图建立一个SQL查询,只恢复一个表(它已经有一个时间戳列)中最年轻的记录,我想过滤的项目出现了几次,如我的表示例所示。

table example.

基本上,我有一个 table1 与Id、Millis、fkName和Price,以及一个。table2 与Id和Name。

table1我需要实现的是建立一个单一的查询,在这个查询中,我可以列出每个fkName的最后一条记录,这样我就可以得到每个商品的最实际价格。

我需要实现的是建立一个单一的查询,在这个查询中,我可以列出每个fkName的最后一条记录,这样我就可以得到每个项目的最实际价格。

到目前为止,我所尝试的是一个查询,其中包含了

SELECT DISTINCT [table1].[Millis], [table2].[Name], [table1].[Price]
FROM [table1]
JOIN [table2] ON [table2].[Id] = [table1].[fkName]
ORDER BY [table2].[Name]

但我没有得到正确的列表。

有什么建议吗?先谢谢你了。

sql sql-server tsql join greatest-n-per-group
2个回答
2
投票

解决这个最大-n-每组问题的一个简单而可移植的方法是用子查询进行过滤。

select t1.millis, t2.name, t1.price
from table1 t1
inner join table2 t2 on t2.id = t1.fkName
where t1.millis = (select max(t11.millis) from table1 t11 where t11.fkName = t1.fkName)
order by t1.millis desc

1
投票

使用通用表表达式。

;with [LastPrice] as (
    select [Millis], [Price], ROW_NUMBER() over (Partition by [fkName] order by [Millis] desc) rn
    from [table1] 
)
SELECT DISTINCT [LastPrice].[Millis],[table2].[Name],[LastPrice].[Price]
FROM [LastPrice]
JOIN [table2] ON [table2].[Id] = [LastPrice].[fkName]
WHERE [LastPrice].rn = 1
ORDER BY [table2].[Name]
© www.soinside.com 2019 - 2024. All rights reserved.