简体   繁体   English

Oracle SQL基于列的最大值返回单行

[英]Oracle SQL Return Single Row Based On Max Value of a Column

I have in my database table 我在数据库表中

a | 一个| 1 1个

a | 一个| 2 2

a | 一个| 3 3

a | 一个| 4 4

How should I return only with a SELECT query: 我应该如何仅使用SELECT查询返回:

a | 一个| 4 4

I have tried several combination with distinct and max values but all seem to be irrelevant. 我尝试了几种不同的值和最大值的组合,但似乎都无关紧要。

SELECT MAX(a) AS a FROM <TABLE>

Edit: I thought "a" was the name of the column, if it is another column, use 编辑:我以为“ a”是列的名称,如果它是另一列,请使用

SELECT col1, MAX(col2) FROM <TABLE> GROUP BY col1

which will return one row per col1 value. 每个col1值将返回一行。 If there are other values there (like b, c), it depends on what you want. 如果那里还有其他值(如b,c),则取决于您要的内容。

the query is this: 查询是这样的:

select * from yourTable 
where B = (select max(B) from yourTable);

I am assuming you dont just want to get a|4 but there are other similar combinations like b|3, c|6 etc, So assuming the columns are c1, c2, the query would be 我假设您不只是想要得到a | 4,但是还有其他类似的组合,例如b | 3,c | 6等,因此,假设列为c1,c2,则查询为

select * from table_1 where (c2) in (select max(c2) from table_1 group by c1)

If your table is like 如果你的桌子像

C1|C2
a|1
a|2
a|4
b|3
c|2
c|6

the output would be like 输出会像

a|4
b|3
c|6

You can use analytic functions for this (assuming the name column contains the 'a' and the value column contains 1,2,3,4, ...): 您可以为此使用解析函数(假设名称列包含'a',而值列包含1,2,3,4,...):

select * from (
  select name, value, rownum over (partition by 1 order by value desc) 
  as rn
  from mytable)
where rn = 1

Or, you can use a plain old ORDER BY: 或者,您可以使用普通的旧ORDER BY:

select * from (
  select name, value
  from mytable
  order by value desc)
where rownum = 1

Assuming your table T has two columns C1 and C2, have you tried it following way? 假设您的表T有两列C1和C2,您是否按照以下方式尝试过?

select C1, C2 from T where C2 in (select max(C2) from T)

EDIT - I tried mine as well as other suggested answers, and to my surprise, this one is working best for me, even though I have to do full table scan in the sub-query. 编辑-我尝试了我的以及其他建议的答案,令我惊讶的是,即使我必须在子查询中进行全表扫描,该选项也对我来说效果最好。 If you've got what you were looking for, could you please share it with us, or mark the best answer? 如果您有想要的东西,可以与我们分享一下,或者标记为最佳答案吗?

Try like this. 尝试这样。

select Col_A,Col_B
from Table_X
where Col_B =(select max(Col_B) from Table_X)

如果给定的a是表中的值,则可以使用

select column_name, max(coulumn_b) from table_name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM