一尘不染

Oracle SQL GROUP BY“提供GROUP BY表达式”帮助

sql

我有一个表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 123。我想到的最明显的查询是

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抛出“ ”异常。我尝试添加的所有其他领域(例如idvalue在中)GROUP BY条款,但只是回报的一切,就好像没有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)?谢谢你。


阅读 218

收藏
2021-03-17

共1个答案

一尘不染

 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
2021-03-17