如何显示每个项目的第二个最早的日期
我只显示查询的最大日期:
SELECT
item_id,
MAX(post_date)
FROM market_price
GROUP BY item_id
如何显示每个项目的第二个最旧/第二个最长日期?
答案 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()
的效果。
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