Select 列中的下一个最大值

Select the next greatest value from a column

我正在使用 SQL 服务器,我有一个 table 看起来像这样的服务器(表 1)。我想通过 运行 一个 select 语句展望 table 中下一个最大的 AccountId 值。

表 1

CompanyId AccountId CustomerId
1 14 2
1 14 5
1 17 3
1 18 1
1 18 2
2 7 3
2 7 4
2 25 1

我试过使用 lead() 但这不是我想要的。它只是展望下一个 'AccountId',而不是下一个最伟大的。我只想展望相同的 'CompanyId' 和每次 'AccountId' 变化。

Select lead(AccountId, 1) over (partition by CompanyId order by CompanyId, CustomerId) as NextAccountId
From Table1

这是我想要的结果

CompanyId AccountId CustomerId NextAccountId
1 14 2 17
1 14 5 17
1 17 3 18
1 18 1 NULL
1 18 2 NULL
2 7 3 25
2 7 4 25
2 25 1 NULL

这可以通过一个简单的相关子查询来完成:

select *, (
  select Min(t2.accountId) 
  from t t2 
  where t2.CompanyId=t.CompanyId and t2.accountId > t.accountId 
) as NextAccountId
from t;

您可以完全使用 window 函数来完成此操作,并且 只扫描基 table 一次

SELECT *,
  NextAccount = MAX(NextRow) OVER (PARTITION BY CompanyId, AccountId)
FROM (
    SELECT *,
      NextRow = NULLIF(LEAD(AccountId) OVER (PARTITION BY CompanyId ORDER BY AccountId), AccountId)
    FROM Table1
) t

我们使用 LEADAccountId 排序来获取下一行的值。如果它等于当前行,我们将其清空。

然后 MAXMIN,同时按 AccountId 进行分区(而不是排序),我们得到分区中唯一的非空值。

db<>fiddle