根据排序结果选择条件+另一个条件

pxyaymoc  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(333)
date      action 
----------   -------
2018-01-12   acquire
2018-01-14   release
2018-01-15   acquire
2018-01-19   release

我需要选择where date>='2018-01-13',但只能从某个'acquire'行(按date asc排序)中选择,因此结果将是

2018-01-15   acquire
2018-01-19   release

(从满足条件之日后的首次收购开始)。用一个sql语句可以吗?

zpf6vheq

zpf6vheq1#

获取满足条件的最小日期,然后选择日期从该日期开始的所有行。

SELECT date, action
FROM yourTable
WHERE date >= (
    SELECT MIN(date)
    FROM yourTable
    WHERE date >= '2018-01-13' AND action = 'acquire'
)
jexiocij

jexiocij2#

SELECT a.* 
  FROM my_table a 
  JOIN my_table b 
    ON b.date <= a.date 
 WHERE b.date >= '2018-01-13' 
   AND b.action = 'acquire';
qpgpyjmq

qpgpyjmq3#

假设你想得到每个动作的第一个日期。。。

SELECT `date`, `action`
FROM theTable
WHERE (`date`, `action`) IN (
   SELECT MIN(`date`), `action`
   FROM theTable
   WHERE `date` > '2018-01-13'
   GROUP BY `action`
)

相关问题