选择满足某些条件并在特定列中具有最大值的行

编程入门 行业动态 更新时间:2024-10-28 02:31:34
本文介绍了选择满足某些条件并在特定列中具有最大值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个元数据表,用于更新软件包。该表具有列 id,名称,版本。我要选择名称是给定名称列表之一的所有行,并且该版本是具有该名称的所有行的最大值。

I have a table of metadata for updates to a software package. The table has columns id, name, version. I want to select all rows where the name is one of some given list of names and the version is maximum of all the rows with that name.

例如,给定这些记录:

+----+------+---------+ | id | name | version | +----+------+---------+ | 1 | foo | 1 | | 2 | foo | 2 | | 3 | bar | 4 | | 4 | bar | 5 | +----+------+---------+

还有一个任务给我记录的最高版本 foo和 bar,我希望结果是:

And a task "give me the highest versions of records "foo" and "bar", I want the result to be:

+----+------+---------+ | id | name | version | +----+------+---------+ | 2 | foo | 2 | | 4 | bar | 5 | +----+------+---------+

我想出了什么到目前为止,使用的是嵌套查询:

What I come up with so far, is using nested queries:

SELECT * FROM updates WHERE ( id IN (SELECT id FROM updates WHERE name = 'foo' ORDER BY version DESC LIMIT 1) ) OR ( id IN (SELECT id FROM updates WHERE name = 'bar' ORDER BY version DESC LIMIT 1) );

这可行,但感觉不对。如果我想过滤更多名称,我必须多次复制整个子查询。有更好的方法吗?

This works, but feels wrong. If I want to filter on more names, I have to replicate the whole subquery multiple times. Is there a better way to do this?

推荐答案

select distinct on (name) id, name, version from metadata where name in ('foo', 'bar') order by name, version desc

更多推荐

选择满足某些条件并在特定列中具有最大值的行

本文发布于:2023-10-27 16:20:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533908.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:并在   最大值   条件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!