用于从一个表中获取少量内容的SQL查询

时间:2018-06-11 19:46:05

标签: sql oracle

我的一个表有问题。表格如下:

+----------+------------+-------------+------+
| index_id | version_id |    date     | type |
+----------+------------+-------------+------+
|        1 |          4 | today       | C    |
|        1 |          2 | last month  | C    |
|        1 |          4 | today       | U    |
|        2 |          3 | yesterday   | c    |
|        2 |          4 | today       | C    |
|        2 |          2 | last year   | U    |
|        3 |          7 | yesterday   | C    |
|        3 |          6 | last month  | C    |
|        3 |          8 | today       | U    |
+----------+------------+-------------+------+

我想要实现的是获取两种类型的最大版本和最大日期的索引(index_id)。

像这样:

+----------+------------+-----------+------+
| index_id | version_id |   date    | type |
+----------+------------+-----------+------+
|        1 |          4 | today     | C    |
|        1 |          4 | today     | U    |
|        2 |          4 | today     | C    |
|        2 |          3 | yesterday | U    |
|        3 |          7 | yesterday | C    |
|        3 |          8 | today     | U    |
+----------+------------+-----------+------+

我想问你一些关于这个问题的想法。感谢。

3 个答案:

答案 0 :(得分:1)

我会选择row_number()

select t.*
from (select t.*,
             row_number() over (partition by index_id, type order by version_id desc) as seqnum
      from t
     ) t
where seqnum = 1;

答案 1 :(得分:1)

使用row_numberpartition获取给定index_id和类型组合的每个组的最大值

select index_id,version_id,date,type from 
(
    select *, row_number() over (partition by index_id,type order by version_id,desc) as r_no
    from table
) a
where a.r_no = 1

答案 2 :(得分:0)

我会使用subquery

select t.*
from table t
where version_id = (select max(t1.version_id) 
                    from table t1 
                    where t1.index_id = t.index_id and 
                          t1.type = t.type 
                   );