我们说我们有下一个数据
id | date | price
------------------------
1 | 10-09-2016 | 200
2 | 11-09-2016 | 190
3 | 12-09-2016 | 210
4 | 13-09-2016 | 220
5 | 14-09-2016 | 200
6 | 15-09-2016 | 200
7 | 16-09-2016 | 230
8 | 17-09-2016 | 240
我们必须先按日期订购,然后按价格订购,但是如果价格必须按顺序排列。如果当前价格低于先前价格,我们应该省略此行,结果将是:
id | date | price
------------------------
1 | 10-09-2016 | 200
3 | 12-09-2016 | 210
4 | 13-09-2016 | 220
7 | 16-09-2016 | 230
8 | 17-09-2016 | 240
没有加入是否可能?
答案 0 :(得分:2)
使用LAG
窗口功能
SELECT *
FROM (SELECT *,
Lag(price)OVER( ORDER BY date) AS prev_price
FROM Yourtable) a
WHERE price > prev_price
OR prev_price IS NULL -- to get the first record
答案 1 :(得分:1)
如果“previous”应该表示输出中的上一行,则跟踪运行的最大值。在子查询中带有window function的Postgres解决方案:
SELECT id, date, price
FROM (
SELECT *, price >= max(price) OVER (ORDER BY date, price) AS ok
FROM tbl
) sub
WHERE ok;
答案 2 :(得分:0)
如果Postgres:
select id, date, price
from
(select
t.*,
price - lag(price, 1, price) over (order by id) diff
from
your_table) t
where diff > 0;
如果是MySQL:
select id, date, price from
(
select t.*,
price - @lastprice diff,
@lastprice := price
from
(select *
from your_table
order by id) t
cross join (select @lastprice := 0) t2
) t where t.diff > 0;