SQL:查询显示最大日期(第一个和第二个最大日期)

时间:2017-12-15 02:48:43

标签: mysql sql

如何显示每个项目的第二个最早的日期

https://i.stack.imgur.com/NN17o.png

我只显示查询的最大日期:

SELECT
  item_id,
  MAX(post_date)
FROM market_price
GROUP BY item_id

https://i.stack.imgur.com/Gi443.png

如何显示每个项目的第二个最旧/第二个最长日期?

2 个答案:

答案 0 :(得分:1)

我认为这适用于MySQL:

select mp.*
from market_price mp
where mp.post_date = (select mp2.post_date
                      from market_price mp2
                      where mp2.item = mp.item
                      order by mp2.post_date
                      offset 1 limit 1
                     );

答案 1 :(得分:0)

在MySQL将窗口函数引入已发布版本之前,您可以使用有序子查询和一些变量来模仿row_number() over()的效果。

SQL Fiddle

提供演示

MySQL 5.6架构设置

CREATE TABLE market_price 
    (`item_id` varchar(3), `post_date` datetime)
;

INSERT INTO market_price 
    (`item_id`, `post_date`)
VALUES
    ('abc', '2017-12-01 00:00:00'),
    ('abc', '2017-12-02 00:00:00'),
    ('abc', '2017-12-03 00:00:00'),
    ('def', '2017-12-04 00:00:00'),
    ('def', '2017-12-05 00:00:00'),
    ('def', '2017-12-06 00:00:00'),
    ('def', '2017-12-07 00:00:00'),
    ('def', '2017-12-08 00:00:00')
;

查询1

SELECT
        item_id
      , post_date
FROM (
      SELECT
            @row_num :=IF(@prev_value=item_id,@row_num+1,1) AS rn
          , mp.item_id
          , mp.post_date
          , @prev_value := item_id
      FROM market_price mp
      CROSS JOIN (SELECT @row_num :=1,  @prev_value :='') vars
      ORDER BY
            mp.item_id
          , mp.post_date DESC
    ) d
WHERE rn = 2
;

<强> Results

| item_id |            post_date |
|---------|----------------------|
|     abc | 2017-12-02T00:00:00Z |
|     def | 2017-12-07T00:00:00Z |

当/ row_number() over()可用时,请使用:

select
*
from (
     select *
          , row_number() over(partition by item_id order by post_date desc) rn
     from market_price
     ) d
where rn = 2