代码之家  ›  专栏  ›  技术社区  ›  Rober

按年查询

  •  0
  • Rober  · 技术社区  · 6 年前

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

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

    3 回复  |  直到 6 年前
        1
  •  0
  •   Asad ullah    6 年前

    SELECT MIN(daily_price) as minDailyPrice, Max(weekly_price) as maxWeeklyPrice 
    FROM yourTable 
    WHERE until <= 'current_year_here' 
    ORDER BY until DESC 
    LIMIT 1
    
        2
  •  0
  •   Rober    6 年前

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

    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;
    
        3
  •  0
  •   ScaisEdge    6 年前

      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