对于下表:
attr1 date
================
a 2016-12-21
a 2016-11-15
a 2015-04-15
b 2016-10-15
b 2013-10-15
b 2011-10-15
c 2015-01-01
d 2014-02-02
我想得到attr1 = a和date = max(inputDate x)的行,其中x< = date。
另外,对于attr1 = b和输入日期y,以及其他几个属性和日期也一样。
对于单个日期值,解决方案类似于:
SELECT MAX(no) no
FROM table1
WHERE no < 10
(参见: MySql select next lower number without using limit)
问题:
如何通过单个选择来解决这个问题,以便日期(x,y,...)和请求的attr1值分别在:list
个条目中 - 它应该是这样的:
select * from table where attr1 in (..., ..., ...) .... and date in (x, y, ...
答案 0 :(得分:1)
解决方案是在子查询中包含参数列表:
select mytable.attr1, max(mytable.dt)
from
(
select 'a' as attr1, '2015-11-20' as dt
union all
select 'b' as attr1, '2015-11-19' as dt
union all
select 'c' as attr1, '2015-11-18' as dt
union all
select 'd' as attr1, '2013-01-01' as dt
) params
join mytable on mytable.attr1 = params.attr1 and mytable.dt >= params.dt
group by mytable.attr1;