我有类似的数据:
id, id2, datetime_created
1, 1, 9/10
1, 2, 9/9
1, 3, 9/8
2, 4, 9/8
2, 5, 9/2
2, 6, 9/1
3, 7, 9/3
3, 8, 9/4
3, 9, 9/5
预期输出:
id, id2
1, 1
2, 4
3, 9
我尝试了很多事情,包括:
SELECT id, id2, MAX(datetime_created)
FROM table
GROUP BY id2
SELECT id, id2, MAX(datetime_created)
FROM table
GROUP BY id, id2
,
SELECT id, id2
FROM table
INNER JOIN (
SELECT MAX(datetime_created), id
FROM table)
This问题还不够。没有GROUP BY
的情况下,踢球者是GROUP BY
一个与我需要的字段不同的字段,因为它返回了太多行(从我的样本数据集中,它会返回所有行)。
答案 0 :(得分:2)
使用row_number() over()
代替group by
:
SELECT
id, id2, datetime_created
FROM (
SELECT
id, id2, datetime_created
, ROW_NUMBER() OVER (PARTITION BY id ORDER BY datetime_created DESC) AS rn
FROM table1
) d
WHERE rn = 1
这将使您可以访问具有最大datetime值的整个行
答案 1 :(得分:1)
您可以尝试以下操作:
SELECT id, id2
FROM table
WHERE (id, datetime_created) in
(
SELECT id, MAX(datetime_created)
FROM table
GROUP BY id
)
ORDER BY id;
Rextester Demo [P.S。即使在Oracle中,相同的逻辑也有效]
答案 2 :(得分:0)
这可以帮助您:
SELECT tt.id,tt.id2 FROM table tt LEFT JOIN (SELECT id, MAX(datetime_created) AS cr
FROM table
GROUP BY id)q ON q.id=tt.id AND q.cr=tt.datetime_created WHERE q.id IS NOT NULL;