简体   繁体   中英

How to use CTE to do recursive for previous row?

I have a problem which I believe can be solve using the CTE.

I create sql query shown below :

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

I got the results like below: 在此处输入图片说明

What I would like to get is like shown below : 在此处输入图片说明

Basically I would like to have 'y' to be increment by 50 for each row. Is there any way for this?

Thanks in advance.

You need an ordering, but row_number() will do this:

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

? is for the column that specifies the ordering.

As your sample from above:

This will start from 0 and Add 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM