过滤 row_number() 为 1 的记录

Filter records where row_number() is 1

select 
    account_num,load_date, xyz, abc, pqr
    row_number() over(partition by account_num order by load_date desc) as rn
from 
    balance,
where 
    tran_code = 123

我正在获取 o/p 这段代码。现在我想提取那些 rn = 1 的行。有人可以帮我吗?

使用常见的 table 表达式:

with b as ( 
   select account_num, load_date, xyz, abc, pqr
      row_number() over(partition by load_date order by load_date desc) as rn
    from balance
    where tran_code = 123
)
select account_num, load_date, xyz, abc, pqr
from b
where rn=1;

请注意,在某些数据库(例如 Teradata、BigQuery)上,我们可以避免正式的子查询,而是使用 QUALIFY 子句:

SELECT account_num, load_date, xyz, abc, pqr
FROM balance
WHERE tran_code = 123
QUALIFY ROW_NUMBER() OVER (PARTITION load_date ORDER BY <col>) = 1;

在 SQL 服务器上,我们可以使用 TOP 1 WITH TIES 技巧避免子查询:

SELECT TOP 1 WITH TIES account_num, load_date, xyz, abc, pqr
FROM balance
WHERE tran_code = 123
ORDER BY ROW_NUMBER() OVER (PARTITION load_date ORDER BY <col>);

您对 ROW_NUMBER 的调用应该有一个 ORDER BY 子句才有意义。