我有一个价格为
的mysql表id element_id daily_price weekly_price since until
----------------------------------------------------------------------
1 2 400 2800 2017-01-01 2017-05-31
2 2 500 3500 2017-06-01 2017-12-31
3 2 600 4200 2018-01-01 2018-05-31
4 2 700 4900 2018-06-01 2018-12-31
我想做一个查询,以获取当前年份的最低Daily_price和weekly_price。如果没有为当前年度设置价格,那么它应该获得与去年相同的最低价格。
答案 0 :(得分:0)
您可以使用此
SELECT MIN(daily_price) as minDailyPrice, Max(weekly_price) as maxWeeklyPrice
FROM yourTable
WHERE until <= 'current_year_here'
ORDER BY until DESC
LIMIT 1
答案 1 :(得分:0)
您可以将联接与年份,每天的最小和每周的最小子查询一起使用
select a.id, a.year, b. min_daily, c.min_weekly
from (
select id, max(year(until)) year
from my_table
group by id
) a
inner join (
select id, year(until) year, min(daily_price) min_daily
from my_table
group by id , year(until)
) b on a.id = b.id and a.year=b.year
inner join (
select id, year(until) year, min(weekly_price) min_weekly
from my_table
group by id , year(until)
) c on a.id = c.id and a.year=c.year
答案 2 :(得分:0)
我认为这是最简单的方法:
select min(daily_price), min(weekly_price)
from table
where element_id = 2
AND year(since) = (select max(year(since))
from table
where element_id = 2);
或者如果您想使用联接而不是子查询,则执行以下操作:
select min(daily_price), min(weekly_price)
from table a, (select max(year(since)) as year, element_id
from table
where element_id = 2) b
where a.element_id = 2
and a.element_id = b.element_id
and year(since) = b.year;