如何编写sql查询以获得以下结果

时间:2017-12-27 11:23:20

标签: sql sql-server

我有一张包含以下数据的表格。

actual table data

预期结果将低于数据。

Expected table data

此处step1完成日期为step2的到达日期,step2完成日期为step3的到达日期。

如何编写SQL查询以获得此结果。

5 个答案:

答案 0 :(得分:0)

此脚本提供您的预期结果

<?php
    date_default_timezone_set("Asia/Kolkata");
    echo "Today is " . date("Y/m/d") . "<br>";
    echo "Today is " . date("Y.m.d") . "<br>";
    echo "Today is " . date("Y-m-d") . "<br>";
    echo "Today is " . date("l");
    echo "The time is " . date("h:i:sa");
?>

结果

;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

答案 1 :(得分:0)

这应该符合您的目的,完成日期为下一个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

答案 2 :(得分:0)

根据id列的升序排列行号。(如果id列有任何间隙)。然后使用LEFT JOIN / RIGHT JOINrn = rn + 1

<强>查询

;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];

答案 3 :(得分:-1)

some_logical_grouping_of_data定义可用于的数据组。

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;

答案 4 :(得分:-1)

基于字符串后缀加入数据是个坏主意。我假设step1始终具有ID 1step13始终具有ID 13,依此类推。然后你可以做类似

的事情
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;