使用过滤器和日期选择倒数第二个记录

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

我想选择一个倒数第二条记录(按日期)使用产品名称如何过滤。

使用此查询,我选择我有记​​录的所有日期。

select distinct(lstfchdes) from precios (nolock) where lstfchdes > '01/01/2018'
order by lstfchdes desc

在红色框上的图像标记倒数第二个记录。

我使用distinct因为我在确定的日期有多个寄存器。

通过此查询,我选择倒数第二条记录。

SELECT lstfchdes FROM precios (nolock)
WHERE lstfchdes = (SELECT MAX(lstfchdes)
                   FROM precios (nolock)
                   WHERE lstfchdes < (SELECT MAX(lstfchdes)  
                   FROM precios (nolock)))

多数民众赞成找到了。请参阅图像2.我在此查询中不使用distinct,因此在日期中看到多个寄存器的逻辑也是如此。 (将此结果与Image1进行比较)

我的问题是当我在查询中应用过滤器时,例如:

select * from precios (nolock)
WHERE prdid='PRO167' and lstid='L04'
order by lstpfchupd desc

倒数第二的记录是2018-03-03。

但是如果我执行这个查询:

SELECT lstfchdes FROM precios (nolock)
WHERE lstfchdes = (SELECT MAX(lstfchdes)
                   FROM precios (nolock)
                   WHERE lstfchdes < (SELECT MAX(lstfchdes)  
                   FROM precios (nolock)))
and prdid='PRO167' and lstid='L04'

结果返回如果在2018-03-05之外的倒数第二条记录:

可能是什么问题呢?

sql sql-server
1个回答
0
投票

您需要为所有SELECT语句应用过滤器。这是因为您的聚合还需要将过滤器应用于它们。否则你的MAX和类似的聚合将没有过滤器,并将导致不正确的结果。

© www.soinside.com 2019 - 2024. All rights reserved.