按年查询

pprl5pva  于 2021-06-19  发布在  Mysql
关注(0)|答案(3)|浏览(220)

我有一张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

我想做一个单一的查询,得到最低的每日价格和每周价格为目前的一年。如果没有为本年度设定价格,则应获得与去年相同的最低价格。

yshpjwxd

yshpjwxd1#

我认为这是最简单的方法:

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;
fnx2tebb

fnx2tebb2#

您可以将join与year、min daily和min weekly子查询一起使用

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
oaxa6hgo

oaxa6hgo3#

你可以用这个

SELECT MIN(daily_price) as minDailyPrice, Max(weekly_price) as maxWeeklyPrice 
FROM yourTable 
WHERE until <= 'current_year_here' 
ORDER BY until DESC 
LIMIT 1

相关问题