SQL按两列排序,如果第二列不';我不符合命令
假设我们有下一个数据SQL按两列排序,如果第二列不';我不符合命令,sql,Sql,假设我们有下一个数据 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 | 23
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
不使用join可以吗?使用
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
使用
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
如果是博士后:
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;
如果是博士后:
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;
如果“previous”应该是指输出中的前一行,那么请跟踪正在运行的最大值。子查询中包含的Postgres解决方案:
SELECT id, date, price
FROM (
SELECT *, price >= max(price) OVER (ORDER BY date, price) AS ok
FROM tbl
) sub
WHERE ok;
如果“previous”应该是指输出中的前一行,那么请跟踪正在运行的最大值。子查询中包含的Postgres解决方案:
SELECT id, date, price
FROM (
SELECT *, price >= max(price) OVER (ORDER BY date, price) AS ok
FROM tbl
) sub
WHERE ok;
mysql还是postgres?
Postgresql
mysql
是两个不同的数据库引擎,您使用哪一个?没关系,任何解决方案都可以让我在Postgresql
上写下答案,它甚至不会在mysql
上编译,如果第6行的价格是210呢?结果会是这样吗?IOW:“先前”是如何定义的?在输入或输出之前?mysql或postgres?Postgresql
mysql
是两个不同的数据库引擎,您使用哪一个?不要紧,任何解决方案都可以在Postgresql
上写答案,它甚至不会在mysql
上编译,如果第6行有价格210呢?结果会是这样吗?IOW:“先前”是如何定义的?以前的输入或输出?很好的解决方案!然而,ORDERBY条款不应该也包含价格吗?很好的解决方案!然而,订单条款不也应该包含价格吗?