I have a table with below data.
And the expected result will be below data.
Here step1 completion date is arrival date of step2 and the step2 completion date is arrival date of step3.
How to write SQL query to get this result.
This Script gives your expected Result
;With Cte(
id,StepName,ArrivalDate,duedate
)
AS
(
SELECT 1,'Step1','25/12/2017','1/1/2018' UNION ALL
SELECT 2,'Step2','26/12/2017','1/1/2018' UNION ALL
SELECT 3,'Step3','27/12/2017','1/1/2018'
)
SELECT
id
,StepName
,ArrivalDate
,duedate
,ISNULL(LEAD(ArrivalDate,1)OVER(ORDER BY ArrivalDate),'') AS CompletionDate
FROM CTE
Result
id StepName ArrivalDate duedate CompletionDate
-----------------------------------------------------
1 Step1 25/12/2017 1/1/2018 26/12/2017
2 Step2 26/12/2017 1/1/2018 27/12/2017
3 Step3 27/12/2017 1/1/2018
This should serve your purpose, completion date as startdate from next id
SELECT x.id
,x.stepname
,x.arrival_date
,x.due_date
,isnull(y.arrival_date, '') Completion_date
FROM x
LEFT JOIN (
SELECT id
,step1
,step2
,arrival_date
FROM x
) y ON x.id = y.id + 1
Give a row number based on ascending order of id
column.(If id
column has any gaps). Then use a LEFT JOIN
/ RIGHT JOIN
with rn = rn + 1
.
Query
;with cte as(
select [rn] = row_number() over(
order by [id]
), *
from [your_table_name]
)
select t1.[stepName], t1.[ArrivalDate], t1.[dueDate],
coalesce(t2.[dueDate], '') as [completiondate]
from cte t1
left join cte t2
on t1.[rn] + 1 = t2.[rn];
some_logical_grouping_of_data shoud define group of data which can be used for.
Select ID, stepname, arrival_date, duedate,
LEAD ( arrival_date) OVER ( partition by "some_logical_grouping_of_data" order by ID) as completion_date
from table;
It's a bad idea to join data based on String suffixes. I assume that step1
always has ID 1
, step13
always has ID 13
and so on. Then you can do something like
SELECT t1.ID, t1.Stepname, t1.arrival_date, t2.arrival_date as completion_date
FROM tablename t1
LEFT JOIN tablename t2 on t1.ID + 1 = t2.ID;
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.