MySQL在多列中选择max

时间:2018-02-07 21:50:12

标签: mysql greatest-n-per-group

我有一张按日期显示股票价格的表格,我想选择最接近多个日期的价值。例如,给我一个与今天,一个月前和两个月前最接近的价格。我可以在单独的语句中完成它,是否可以在单个语句中执行?

在下面,我想返回第1,2和6行作为最接近2 / 7,1 / 7和12/7日期(最好使用abs()这样做?)

+---+------------+---------+----------------+----------------+----------------+
| d | quotedate  |  price  | 2018-02-07diff | 2018-01-07diff | 2017-12-07diff |
+---+------------+---------+----------------+----------------+----------------+
| 1 | 2018-02-06 |  13.796 |             -1 |             30 |             61 |
| 2 | 2018-01-09 | 14.1135 |            -29 |              2 |             33 |
| 3 | 2018-01-02 |  13.822 |            -36 |             -5 |             26 |
| 4 | 2017-12-27 | 13.7365 |            -42 |            -11 |             20 |
| 5 | 2017-12-22 |   13.75 |            -47 |            -16 |             15 |
| 6 | 2017-12-04 |  13.589 |            -65 |            -34 |             -3 |
| 7 | 2017-11-28 |  13.477 |            -71 |            -40 |             -9 |
| 8 | 2017-10-31 |  13.214 |            -99 |            -68 |            -37 |
+---+------------+---------+----------------+----------------+----------------+

我已经让它做了一行,但是我希望能够一次完成所有3行吗? 小提琴:Here

1 个答案:

答案 0 :(得分:1)

select p1.id, p1.name,
  DATE_FORMAT(p1.quote_date, "%Y-%m-%d") as quotedate,
  p1.price,
  DATEDIFF( p1.quote_date, '2018-02-07' ) as 'diff1',
  DATEDIFF( p1.quote_date, '2018-01-07' ) as 'diff2',
  DATEDIFF( p1.quote_date, '2017-12-07' ) as 'diff3'
from prices p1
left outer join (select id, name, quote_date, price, 
                 DATEDIFF( quote_date, '2018-02-07' ) as 'diff1p2'
                 FROM prices) p2
on (p1.name = p2.name
   AND DATEDIFF( p1.quote_date, '2018-02-07' )< diff1p2
    AND DATEDIFF( p1.quote_date, '2018-02-07' ) <=0


   )
WHERE p1.name = 'Stock1'
AND p2.id is null
union
    select p1.id, p1.name,
  DATE_FORMAT(p1.quote_date, "%Y-%m-%d") as quotedate,
  p1.price,
  DATEDIFF( p1.quote_date, '2018-02-07' ) as 'diff1',
  DATEDIFF( p1.quote_date, '2018-01-07' ) as 'diff2',
  DATEDIFF( p1.quote_date, '2017-12-07' ) as 'diff3'
from prices p1
left outer join (select id, name, quote_date, price, 
                 DATEDIFF( quote_date, '2018-01-07' ) as 'diff1p2'
                 FROM prices) p2
on (p1.name = p2.name
   AND DATEDIFF( p1.quote_date, '2018-01-07' )< diff1p2
    AND DATEDIFF( p1.quote_date, '2018-01-07' ) <=0

您应该在3个查询之间使用联合,以便一次获得所有3行