SQL Server:使用语法

问题描述 投票:0回答:2

我有一桌

employeeSomething

tb_EmployeeSomething

EmpID| TypeID
1 | 1
1 | 1
1 | 1
1 | 2
1 | 2
2 | 2
2 | 2
2 | 2

现在我在程序中使用分页,返回必须是

EmpID| TypeID| RowNum
1|1|1
1|2|2
2|2|3

这是我尝试过的

Declare @start int
Declare @end int

With Tmp2 as (
    With Tmp1 as (
        Select Distinct EmpID, TypeID 
        From tb_deductionBalance
    )
    Select *, row_number() OVER ( order by employeeID ) as RowNum 
    From Tmp1
)
Select * From Tmp2
Where RowNum Between @Start and @End

我不确定是否有更好的方法来做到这一点。

sql sql-server server
2个回答
3
投票

您不嵌套公用表表达式(CTE),您用逗号分隔它们:

;With Tmp1 as (
        Select Distinct EmpID, TypeID 
        From tb_deductionBalance
), Tmp2 as (
    Select *,
       row_number() OVER ( order by empID /* no employeeID in Tmp1 */) as RowNum 
    From Tmp1
)
Select * From Tmp2
Where RowNum Between @Start and @End

任何 CTE 都可以引用任何早期的 CTE。


0
投票

使用 ROW_NUMBER() 函数来完成此操作。 您可以在此处找到有关 ROW_NUMBER 的信息: http://technet.microsoft.com/en-us/library/ms189798.aspx

© www.soinside.com 2019 - 2024. All rights reserved.