选择另一列的最大值/最小值

时间:2017-06-05 09:06:58

标签: sql sql-server tsql

有没有办法选择最大值+另一列而不使用 TOP 排序?

假设我们有一个人和他们的年龄列表,我们想要最老/最年轻。我想选择名字+年龄。即使我们想要按照名称对它们进行分组,这也不会起作用。

SELECT   nom,
         max(age) 
from     Agents
group by nom

╔════════╦═════╗
║  Name  ║ Age ║
╠════════╬═════╣
║ John   ║ 200 ║
║ Bob    ║ 150 ║
║ GSkill ║ 300 ║
║ Smith  ║ 250 ║
║ John   ║ 400 ║
║ Zid    ║ 300 ║
║ Wick   ║ 250 ║
║ Smith  ║ 140 ║
╚════════╩═════╝

2 个答案:

答案 0 :(得分:1)

您可以使用ROW_NUMBERDENSE_RANK。例如,如果您必须显示具有MIN和MAX薪水的员工,那么您可以使用以下SQL语句:

SELECT x.Name, x.Salary, 
    IIF(x.RowNumMIN = 1, 1, 0) AS IsMin,
    IIF(x.RowNumMAX = 1, 1, 0) AS IsMax
FROM (
    SELECT x.Name, x.Salary,
        ROW_NUMBER() OVER(ORDER BY x.Salary ASC) AS RowNumMIN,
        ROW_NUMBER() OVER(ORDER BY x.Salary DESC) AS RowNumMAX
    FROM dbo.SourceTable AS x
) AS x
WHERE x.RowNumMIN = 1 OR x.RowNumMAX = 1

如果有两个或更多人拥有相同的最低或最高工资而你必须全部显示,那么你可以使用DENSE_RANK函数而不是ROW_NUMBER。

答案 1 :(得分:1)

尝试此查询 -

;WITH CTE
AS (
    SELECT [NAME]
        ,AGE
        ,DENSE_RANK() OVER (
            ORDER BY AGE DESC
            ) AS Older
        ,DENSE_RANK() OVER (
            ORDER BY AGE ASC
            ) AS Younger
    FROM tblSample
    )
SELECT [NAME] + ': ' + CAST(AGE AS VARCHAR(50))
FROM CTE
WHERE Older = 1 OR Younger = 1