简体   繁体   English

如何在SQL表中获得一组最高Foo

[英]How to get a group of the highest Foo's in a SQL table

I have a SQL table, that contains a column named Foo . 我有一个SQL表,其中包含名为Foo的列。

I know how to get a row with the highest Foo value, with some SQL like this: 我知道如何使用如下这样的SQL获得具有最高Foo值的行:

SELECT MAX(Foo) AS HighestFoo FROM Foos;

How can I get all the rows with the highest Foo? 如何获得Foo最高的所有行?

Use a subquery: 使用子查询:

SELECT
    *
FROM
    Foos
WHERE
    Foo = (SELECT MAX(Foo) AS HighestFoo FROM Foos)

The subquery (on the last line) selects out the highest value, and then uses that value to modify the WHERE clause. 子查询(在最后一行)选择最高值,然后使用该值修改WHERE子句。

An alternative approach (for those db's that support it) is to use dense_rank() over() 另一种方法(对于那些支持它的数据库)是使用density_rank()over()

SELECT
      *
FROM (
            SELECT
                  *
                , DENSE_RANK() OVER (ORDER BY FOO DESC) AS rnk
            FROM tblFoo
      ) AS sq
WHERE rnk = 1
With CTE As (
SELECT MAX(Foo) AS HighestFoo
       FROM Foos
)
Select * From Foos Where Foo = ( Select HighestFoo From CTE)

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

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