我有一个表some_table像
some_table
+--------+----------+---------------------+-------+ | id | other_id | date_value | value | +--------+----------+---------------------+-------+ | 1 | 1 | 2011-04-20 21:03:05 | 104 | | 2 | 2 | 2011-04-20 21:03:04 | 229 | | 3 | 3 | 2011-04-20 21:03:03 | 130 | | 4 | 1 | 2011-04-20 21:02:09 | 97 | | 5 | 2 | 2011-04-20 21:02:08 | 65 | | 6 | 3 | 2011-04-20 21:02:07 | 101 | | ... | ... | ... | ... | +--------+----------+---------------------+-------+
我希望为最新的记录other_id 1,2和3。我想到的最明显的查询是
other_id
1
2
3
SELECT id, other_id, MAX(date_value), value FROM some_table WHERE other_id IN (1, 2, 3) GROUP BY other_id
但是,它会not a GROUP BY expression抛出“ ”异常。我尝试添加的所有其他领域(例如id,value在中)GROUP BY条款,但只是回报的一切,就好像没有GROUP BY条款。(嗯,这也很有意义。)
not a GROUP BY expression
id
value
GROUP BY
所以…我正在阅读Oracle SQL手册,我能找到的一些示例仅涉及具有两或三列的查询以及一些i-have-never-nest-before- before分组功能。我该如何返回
+--------+----------+---------------------+-------+ | id | other_id | date_value | value | +--------+----------+---------------------+-------+ | 1 | 1 | 2011-04-20 21:03:05 | 104 | | 2 | 2 | 2011-04-20 21:03:04 | 229 | | 3 | 3 | 2011-04-20 21:03:03 | 130 | +--------+----------+---------------------+-------+
(每个的最新条目other_id)?谢谢你。
select id, other_id, date_value, value from ( SELECT id, other_id, date_value, value, ROW_NUMBER() OVER (partition by other_id order BY Date_Value desc) r FROM some_table WHERE other_id IN (1, 2, 3) ) where r = 1