Sql 在oracle中比较行值
我的表1有三列:Sql 在oracle中比较行值,sql,oracle,rank,window-functions,Sql,Oracle,Rank,Window Functions,我的表1有三列: Key | Date | Price ---------------------- 1 | 26-May | 2 1 | 25-May | 2 1 | 24-May | 2 1 | 23 May | 3 1 | 22 May | 4 2 | 26-May | 2 2 | 25-May | 2 2 | 24-May | 2 2 | 23 May | 3 2 | 22 May | 4 我想选择值2上次于5月24日更
Key | Date | Price
----------------------
1 | 26-May | 2
1 | 25-May | 2
1 | 24-May | 2
1 | 23 May | 3
1 | 22 May | 4
2 | 26-May | 2
2 | 25-May | 2
2 | 24-May | 2
2 | 23 May | 3
2 | 22 May | 4
我想选择值2上次于5月24日更新的行。使用秩函数对日期进行排序。
我不能得到想要的结果。任何帮助都将不胜感激
SELECT *
FROM (SELECT key, DATE, price,
RANK() over (partition BY key order by DATE DESC) AS r2
FROM Table1 ORDER BY DATE DESC) temp;
您可以尝试以下方法:-
SELECT Date FROM Table1
WHERE Price = 2
AND PrimaryKey = (SELECT MAX(PrimaryKey) FROM Table1
WHERE Price = 2)
另一种看待问题的方式是,您希望找到价格与上次价格不同的最新记录。那么你想要下一张唱片
with lastprice as (
select t.*
from (select t.*
from table1 t
order by date desc
) t
where rownum = 1
)
select t.*
from (select t.*
from table1 t
where date > (select max(date)
from table1 t2
where t2.price <> (select price from lastprice)
)
order by date asc
) t
where rownum = 1;
在许多情况下,我希望第一个版本具有更好的性能,因为只有在最内层的子查询中才能获得maxdate。该verson必须计算滞后,并按顺序进行计算。但是,如果性能是一个问题,您应该在您的环境中对数据进行测试
编辑二:
我最好的猜测是你想要每一把钥匙。您最初的问题并没有提到钥匙,但:
这与Gordon Linoff的第二个选项非常相似,但引入了第二个窗口函数row_number来定位更改价格的最近一行。这将适用于所有或一系列关键点
select
*
from (
select
*
, row_number() over(partition by Key order by [date] DESC) rn
from (
select
*
, NVL(lag(Price) over(partition by Key order by [date] DESC),0) prevPrice
from table1
where Key IN (1,2,3,4,5) -- as an example
)
where Price <> prevPrice
)
where rn = 1
很抱歉,我根本无法测试这一点。您尝试的查询在哪里?选择*从选择主键,日期,价格,按主键排序按日期描述作为r2从表1按日期描述顺序temp我不明白,您想返回pk=3的行而不返回其他行吗?为什么?我提到我想检索上次插入值2的行,然后它没有更改我不想检索其他行,因为我不想要它们。这是一个示例…我不能在sql中硬编码。还有其他行的值可能不同感谢Gordon的回复。如果我在where子句,但多个键失败。我已更新了该问题。您已正确理解该问题。我不理解该键在修改后的问题中所起的作用。当我运行您建议的sql时,修改后的键会干扰结果。如果所有键的值相同,则该键工作正常。
select t1.*
from (select t1.*,
row_number() over (partition by key order by date desc) as seqnum
from (select t1.*,
lag(price) over (partition by key order by date) as prev_price
from table1 t1
) t1
where prev_price is null or prev_price <> price
order by date desc
) t1
where seqnum = 1;
select
*
from (
select
*
, row_number() over(partition by Key order by [date] DESC) rn
from (
select
*
, NVL(lag(Price) over(partition by Key order by [date] DESC),0) prevPrice
from table1
where Key IN (1,2,3,4,5) -- as an example
)
where Price <> prevPrice
)
where rn = 1