如何在sql中找到第n个Term

时间:2011-01-04 03:27:34

标签: sql-server-2005 tsql

我有一张

下的表格
Term
0
8
24
48
80
X

所需的输出

Term1        Term2             Diff

0               8               8

8              24               16

24             48               24

48             80               32

80             x                40

我有以下脚本

Declare @t Table(Term varchar(10))
Insert Into @t 
Select '0' Union All
Select '8' Union All
Select '24' Union All
Select '48' Union All
Select '80' Union All
Select 'X'

到目前为止,我已尝试过

;With Cte1 As
(
    Select rn = ROW_NUMBER() Over(Order By (select 1)),* From @t
)
,cte2 as(
Select 
    Term1 = (Select term from Cte1 where rn=1)
    ,Term2 = (Select term from Cte1 where rn=2)
    ,Diff = Cast((Select term from Cte1 where rn=2) as int) - Cast((Select term from Cte1 where rn=1) as int)
)


Select * from cte2

我不知道在cte2的递归部分做什么..

需要帮助

2 个答案:

答案 0 :(得分:1)

我不确定为什么80x之间的区别应该是40,但是您可以通过调整CTE来返回最后一行所需的内容。

;WITH Cte1 AS
(
  SELECT rn = ROW_NUMBER() OVER (ORDER BY (SELECT 1)), * FROM @t
)
SELECT
  Term1 = Cte1.Term,
  Term2 = (SELECT Term FROM Cte1 AS a_CTE where a_CTE.rn = Cte1.rn + 1),
  Diff = CAST((SELECT CASE Term WHEN 'X' THEN 120 ELSE Term END
               FROM Cte1 AS a_CTE
               WHERE a_CTE.rn = Cte1.rn + 1) AS int)
         - CAST(Cte1.Term AS int)
FROM Cte1
WHERE ISNUMERIC(Cte1.Term) = 1

答案 1 :(得分:0)

我建议使用PIVOT而不是递归CTE。 Cf。:http://msdn.microsoft.com/en-us/library/ms177410.aspx