如何使用CTE对前一行进行递归?

时间:2018-01-03 02:05:16

标签: sql sql-server sql-cte

我有一个问题,我认为可以使用CTE解决。

我创建了如下所示的SQL查询:

with CTE as
(
SELECT Distinct T.testType as name,'tmpRequirement_TestType_Canvas' as template,'n/a' as layout,
0 as x,0 as y,'855' as width,'42' as height,
T.id,T.testType FROM [dbo].[tProperty] P
INNER JOIN tTest_Type T 
on P.tTest_Type_id = T.id)

select * from CTE

我得到如下结果: enter image description here

我想得到的如下所示: enter image description here

基本上我希望'y'每行增加50。有什么办法吗?

提前致谢。

2 个答案:

答案 0 :(得分:1)

您需要订购,但row_number()会执行此操作:

select . . .,
       50 * row_number() over (order by ?) as y
from cte;

?用于指定排序的列。

答案 1 :(得分:0)

作为您上面的样本:

这将从0开始,加50:

select setNumber from 
(select setNumber from
(select 50 * ROW_NUMBER() over(order by id) as setNumber from yourTableOrCTE) as a
union all
select 0) as a order by setNumber