我有以下查询
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/