我有一个sql表
id item date
A apple 2017-09-17
A banana 2017-08-10
A orange 2017-10-01
B banana 2015-06-17
B apple 2014-06-18
如何编写SQL查询,以便对于每个id,我会根据日期获得最近的两个项目。例如:
id recent second_recent
a orange apple
b banana apple
答案 0 :(得分:4)
您可以使用row_number()
和条件聚合:
select id,
max(case when seqnum = 1 then item end) as most_recent,
max(case when seqnum = 2 then item end) as most_recent_but_one,
from (select t.*,
row_number() over (partition by id order by date desc) as seqnum
from t
) t
group by id;
答案 1 :(得分:0)
如上所述: SQL: Group by minimum value in one field while selecting distinct rows
您必须使用A组来获取分钟
SELECT mt.*,
FROM MyTable mt INNER JOIN
(
SELECT item AS recent, MIN(date) MinDate, ID
FROM MyTable
GROUP BY ID
) t ON mt.ID = t.ID AND mt.date = t.MinDate
我认为您可以通过获取两个值而不是一个
来执行相同的操作答案 2 :(得分:0)
您可以使用数据透视表
SELECT first_column AS <first_column_alias>,
[pivot_value1], [pivot_value2], ... [pivot_value_n]
FROM
(<source_table>) AS <source_table_alias>
PIVOT
(
aggregate_function(<aggregate_column>)
FOR <pivot_column> IN ([pivot_value1], [pivot_value2], ... [pivot_value_n])
) AS <pivot_table_alias>;
点击此处了解详情 Example