SQL,OrderBy/GroupBy 问题

标签 sql oracle

在我的表中,我有两个字段:article_idversion

示例:

   article_id | version
   -----------|----------   
        5     |   1
        5     |   2
        6     |   1

我想做的是检索每个文章 ID 的最新版本。 (在我的示例中,我想检索文章 5 版本 2 对象以及文章 6 和版本 1 对象)。

问题是 mysql 正在执行 group by 而不是 order by 所以它返回给我每篇文章的第一个版本,但我想要相反的结果。

你有什么想法吗?

解决方案

select *
from article r
where r.version=(
 select max(version) 
 from article r2 
 where r2.article_id = r.article_id
);

最佳答案

你的问题有点含糊,但我相信这或多或少是你想要的:

select * from (
   select
      <table>.*,
      row_number() over (partition by article_id order by version desc) r  
   from 
      <table>
)
where r = 1

The query returns one record for each (distinct) article_id. This record is the one with the highest version for the article_id returned.

So, together with a "test case", this can be seen in action:

create table tq84_resorces (
  id           number primary key,
  article_id   number not null,
  version      number not null
);

insert into tq84_resorces values (50, 5, 1);
insert into tq84_resorces values (60, 5, 2);
insert into tq84_resorces values (70, 6, 1);


select * from (
   select
      tq84_resorces.*,
      row_number() over (partition by article_id order by version desc) r  
   from 
      tq84_resorces
)
where r = 1

返回:

        ID ARTICLE_ID    VERSION          R
---------- ---------- ---------- ----------
        60          5          2          1
        70          6          1          1

关于SQL,OrderBy/GroupBy 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4958777/

相关文章:

防止位列从 1 更新为 0 的 SQL 触发器?

sql - 查询执行错误期间超出资源,Google BigQuery

sql - 查找跨越周末的连续日期

sql - SQL Server 中的可延迟约束

java - 使用 JSON_TABLE 和 Java 在 Oracle DB 上同时查询 JSON

mysql - 使用 MYSQL 查询以 if 条件连接 2 个表

sql - 如何在SQL中选择相似的集合

mysql - 不能从一个值中减去另一个值(无符号)

java - oracle中将资源加载到java中

oracle - "sqlplus/"的工作原理