如何使用group-by并获取其他行结果

问题描述 投票:0回答:2

问题:如果这是我的数据:

col1,col2,col3,col4
===================
www.com,0,dangerous,reason A
www.com,1,dangerous 2,reason B

我想要第2列值为max的单个结果,所以我将在我的select中使用Max(col2)函数 - 但是如何获得那些相应的col3和col4行?

select 
    col1, max(col2), col3, col4
group by 
    col1

和???

谢谢Idan

sql database group-by
2个回答
0
投票

您可以使用order by并限制为一行。 ANSI标准语法是:

select t.*
from t
order by t.col2 desc
fetch first 1 row only;

并非所有数据库都支持fetch first子句,因此您可能必须使用select top 1limit或其他一些构造。


0
投票

您可以在select语句Like中使用where

Select * from table name where col2=max(col2)

您可以使用单个值获取最大列整行

如果包含相同值的列col2(如此时上面的1,1,2,2)返回2行。那时如果你想要单行你想要使用它

Select * from table name where col2=max(col2) fetch first 1 row only

可能有帮助

© www.soinside.com 2019 - 2024. All rights reserved.