在Where子句中排名

时间:2015-06-29 00:40:19

标签: sql-server tsql

是否可以在Where子句中使用Rank。以下是我打算使用的代码

  Select 
   DebtorID
  ,Rank () over (partition by DebtorID order by BalanceDate) as RankBalanceDate
  ,BalanceDate
  ,Balance
  ,UnallocatedBalance
  ,Overdue
From Debtorbalances
Where Rank () Over (Partition by DebtorID order by BalanceDate) = 1

1 个答案:

答案 0 :(得分:5)

不,这是不可能的。

  

窗口函数只能出现在SELECT或ORDER BY子句中。

您可以使用CTE或子查询来执行此操作:

使用CTE

with Cte AS(
    Select 
        DebtorID
        ,rank() over (partition by DebtorID order by BalanceDate) as RankBalanceDate
        ,BalanceDate
        ,Balance
        ,UnallocatedBalance
        ,Overdue
    From Debtorbalances
)
select * 
from Cte
where 
    RankBalanceDate = 1

使用子查询:

select *
from (
    select 
        DebtorID
        ,rank() over (partition by DebtorID order by BalanceDate) as RankBalanceDate
        ,BalanceDate
        ,Balance
        ,UnallocatedBalance
        ,Overdue
    From Debtorbalances
)t
where 
    RankBalanceDate = 1