SQL查询在2个日期之间或之前的第一个

时间:2015-02-17 14:04:12

标签: mysql sql between

好的,我想查找一段时间内活跃的所有价格。  我有一张桌子"价格"每个价格及其激活日期。

╔══════════════╦═════════════════╗
║ price_number ║ activation_date ║
╠══════════════╬═════════════════╣
║ Price 1      ║ 2014-12-03      ║
║ Price 2      ║ 2014-12-07      ║
║ Price 3      ║ 2014-12-12      ║
║ Price 4      ║ 2014-12-25      ║
╚══════════════╩═════════════════╝

现在我想选择2014-12-09和2014-12-14之间活跃的价格。

价格2和价格3应显示为结果(价格2,因为它在2014-12-09和2014-12-12之间有效,直到价格3被激活)。

所以基本上我希望价格的激活日期在2014-12-09和2014-12-14之间,或者是2014-12-09之前的第一个。

到目前为止我得到了什么:

SELECT * FROM prices 
WHERE (activation_date BETWEEN '2014-12-09' AND '2014-12-14') 
OR (Something I can't find)

我正在使用MySQL 5.5

2 个答案:

答案 0 :(得分:3)

由于前一行的条件性,这有点复杂。以下是使用union all的一种方法:

(SELECT p.*
 FROM prices p
 WHERE activation_date BETWEEN '2014-12-09' AND '2014-12-14'
) UNION ALL
(SELECT p.*
 FROM prices p
 WHERE activation_date < '2014-12-09' AND
       NOT EXISTS (SELECT 1 FROM prices p2 WHERE activation_date BETWEEN '2014-12-09' AND '2014-12-14')
 ORDER BY activation_date DESC
 LIMIT 1
);

答案 1 :(得分:2)

另一种方式是....

select * from ( select p1.price_number,p1.activation_date, min(dateadd(day,datediff(day,p1.activation_date,p2.activation_date)-1,p1.activation_date)) 'activationdate_end' from prices p1 inner join prices p2 on p1.activation_date < p2.activation_date group by p1.price_number,p1.activation_date ) A where ('2014-12-09' between A.activation_date and A.activationdate_end) or '2014-12-14' between A.activation_date and A.activationdate_end

这是在MSSQL中......但我相信它也可以在MySQL中完成