mysql - 在提供额外选择的同时对查询进行分组

标签 mysql sql oracle postgresql derby

我有以下查询

select t1.file_name, 
       max(create_date), 
       t1.id 
 from dbo.translation_style_sheet AS t1 
GROUP BY t1.file_name

我想将 id 添加到选择中,但每次我这样做时,它都会返回所有结果而不是我的分组结果

我的目标是回归

pdf | 10/1/2012 | 3
doc | 10/2/2012 | 5

但是我的查询正在返回

pdf | 9/30/2012 | 1
pdf | 9/31/2012 | 2
pdf | 10/1/2012 | 3
doc | 10/1/2012 | 4
doc | 10/2/2012 | 5

有人知道我做错了什么吗?

最佳答案

如果您保证具有 max(create_date) 的行也具有最大的 id 值(您的示例数据确实如此,但我不知道那是否是神器),您只需选择 max(id)

select t1.file_name, max(create_date), max(t1.id) 
  from dbo.translation_style_sheet AS t1 
 GROUP BY t1.file_name

如果您不能保证这一点,并且您希望返回具有 max(create_date) 的行中的 id 值,您可以使用解析功能。以下将在 Oracle 中工作,但像 Derby 这样不太复杂的数据库不太可能支持它。

select t1.file_name, t1.create_date, t1.id
  from (select t2.file_name,
               t2.create_date,
               t2.id,
               rank() over (partition by t2.file_name 
                                order by t2.create_date desc) rnk
          from dbo.translation_style_sheet t2) t1 
  where rnk = 1

您还可以使用子查询。这可能比解析函数方法更便携但效率较低

select t1.file_name, t1.create_date, t1.id
  from dbo.translation_style_sheet t1
 where (t1.file_name, t1.create_date) in (select t2.file_name, max(t2.create_date)
                                            from dbo.translation_style_sheet t2
                                           group by t2.file_name);

select t1.file_name, t1.create_date, t1.id
  from dbo.translation_style_sheet t1
 where t1.create_date = (select max(t2.create_date) 
                           from dbo.translation_style_sheet t2
                          where t1.file_name = t2.file_name);

关于mysql - 在提供额外选择的同时对查询进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13093761/

相关文章:

mysql - 如何根据特定列从我想要的行和 "next"行获取属性?

oracle - Oracle SQL 中是否有 HTF.ESCAPE_SC 的内置反函数?

mysql - 添加触发器时表对数据库未知

mysql - 使用 MySQL 设置 MaxScale 读/写分离路由

sql - R - Postgresql 将数据导出到 CSV

sql - 重构 "extreme"SQL 查询

oracle - 对子类型属性的约束 (Oracle)

sql - 最大非空列

java - 使用 hibernate 验证电子邮件是否已在我的数据库中

php - 如何从 PHP 访问我的 json 编码数据到 mysql 查询中