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

时间:2018-03-05 17:46:41

标签: sql sql-server

我想选择倒数第二条记录(按日期),使用产品名称进行过滤。

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

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

Image1

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

我使用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进行比较)

Image2

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

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

Image 3

倒数第二的纪录是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之外的倒数第二条记录:

Image4

可能是什么问题?

1 个答案:

答案 0 :(得分:0)

您需要为所有MAX语句应用过滤器。这是因为您的聚合还需要将过滤器应用于它们。否则,您的Pizza(?p), hasIngredient(?p, ?ing1), hasIngredient(?p, ?ing2), hasCountryOfOrigin(?ing1, ?c1), hasCountryOfOrigin(?ing2, ?c1), differentFrom(?ing1, ?ing2) -> NationalPizza(?p) 和类似的聚合将没有过滤器,并且会导致错误的结果。

相关问题