如何从sql表中获取最大值id

时间:2016-05-19 13:41:59

标签: sql sql-server greatest-n-per-group

我需要从下表中获取每个帐户的最大(金额)值

ID   Account   Amount
1     rx00      100
2     rx00      200
3     rx00      100
4     vxtt       50
5     vxtt       70
6     vxtt       80

我需要一个结果表

ID   Account   Amount
2     rx00      200
6     vxtt       80

请告知上述结果

3 个答案:

答案 0 :(得分:1)

您可以使用ROW_NUMBER

SELECT ID, Account, Amount
FROM (
  SELECT ID, Account, Amount,
         ROW_NUMBER() OVER (PARTITION BY Account 
                            ORDER BY Amount DESC) AS rn
  FROM mytable) AS t
WHERE t.rn = 1 

如果您有联系,即多个记录共享相同的最大Amount值,并且您想要返回所有这些记录,请使用RANK代替ROW_NUMBER

答案 1 :(得分:0)

;With cte
as
(
select id,account,amount
,row_number () over (partition by account order by amount desc) as rn
from
table
)
select * from cte where rn=1

在上面的代码中,为帐户和金额分配的每个值分配了唯一的 RowNumber (以数量的desc顺序排序的值)。因为我们无法直接选择Row_number或任何计算where子句中的值。我使用了虚拟表

答案 2 :(得分:0)

您可以使用 row_number 来获得所需的结果。

    DECLARE @table TABLE 
    (ID int, Account varchar(10),Amount int)

    INSERT INTO @table
    (ID,Account,Amount)
    VALUES
    (1,'rx00',100),
    (2,'rx00',200),
    (3,'rx00',100),
    (4,'vxtt',50),
    (5,'vxtt',70),
    (6,'vxtt',80)

   SELECT ID, Account, Amount
    FROM (
      SELECT ID, Account, Amount,
             ROW_NUMBER() OVER (PARTITION BY Account 
                                ORDER BY Amount DESC) AS rnk
      FROM @table) AS t
    WHERE t.rnk = 1 

这将是输出:

ID  Account Amount
2   rx00    200
6   vxtt    80

如果您不需要结果集中的ID列,则可以使用以下查询。

    SELECT Account,max(Amount)  AS Amount FROM @table t
    GROUP BY Account

这将是输出:

Account Amount 
rx00    200
vxtt    80