我有一个包含以下各列的销售表。我想选择销售价格正在增加的行,而跳过那些降低价格的行,其中上一行的销售价格正在增加。
例如在下表中,我希望除具有saleid=4
+--------+--------+-----------+
| SaleId | ItemId | SalePrice |
+--------+--------+-----------+
| 1 | 987 | 12 |
+--------+--------+-----------+
| 2 | 678 | 13 |
+--------+--------+-----------+
| 3 | 987 | 15 |
+--------+--------+-----------+
| 4 | 542 | 11 |
+--------+--------+-----------+
| 5 | 678 | 16 |
+--------+--------+-----------+
我尝试使用内部联接。但是它什么也没显示。 这是我写的查询:
select s1.* from saletable s1
join saletable s2 on s1.saleid = s2.saleid
where s1.saleprice<s2.saleprice
答案 0 :(得分:1)
使用运行max来考虑以下解决方案
select t.*
from
(
select *, max(SalePrice) over (order by SaleId) runningMaxSalePrice
from testdata
) t
where t.SalePrice >= t.runningMaxSalePrice
此解决方案跳过了多个连续的行,并降低了SalePrice。
答案 1 :(得分:0)
使用lag()
:
select st.*
from (select st.*, lag(saleprice) over (order by saleid ) as prev_saleprice
from saletable st
) st
where prev_saleprice is null or saleprice > prev_saleprice