MySql - Inner Join返回超出指定日期范围的行

时间:2018-02-20 17:45:11

标签: mysql

请参阅以下内容和http://sqlfiddle.com/#!9/c98c57/1

该查询用于在0到180天(过去6个月)内返回最低和最高价格。它确实做到了。但是,如果价格在其他行中找到,超出或在所需范围内,它也会加入数据集......

我只需要它返回,以达到report_term ... 即2018年1月...... 2018年2月......

On LIVE:

enter image description here

由于

select   a.metal_price_datetime
         , t1.highest_gold_price
         , t1.report_term
         , t2.lowest_gold_price
         ,t2.metal_price_datetime

  from metal_prices_v2 a
  inner join (
      SELECT  CONCAT(MONTHNAME(metal_price_datetime), ' ', YEAR(metal_price_datetime)) AS report_term
               , max(metal_price) as highest_gold_price

      from metal_prices_v2
      WHERE metal_id = 1
      AND DATEDIFF(NOW(), metal_price_datetime) BETWEEN 0 AND 180
      GROUP BY report_term
  ) t1 on t1.highest_gold_price = a.metal_price
  inner join (
     select   a.metal_price_datetime
         , t.lowest_gold_price
         , t.report_term

  from metal_prices_v2 a
  inner join (
      SELECT  CONCAT(MONTHNAME(metal_price_datetime), ' ', YEAR(metal_price_datetime)) AS report_term
               , min(metal_price) as lowest_gold_price

      from metal_prices_v2
      WHERE metal_id = 1
      AND DATEDIFF(NOW(), metal_price_datetime) BETWEEN 0 AND 180
      GROUP BY report_term
  ) t on t.lowest_gold_price = a.metal_price

 ) t2 on t2.report_term = t1.report_term

0 个答案:

没有答案