代码之家  ›  专栏  ›  技术社区  ›  LMHull

如何在sql中使用条件遍历嵌套行?

  •  0
  • LMHull  · 技术社区  · 6 年前

    我想创建一个for循环的等价物。我需要这个在SQL中。我的目标是创建一个名为difference的新列,该列计算每行结束与下一行开始之间的日期差(以天为单位)。实质上,我需要知道每个人的合同是否有任何中断。rowid from min to max定义了一个与特定组织的合同,例如每个与一个组织的新合同都以1开头。

    我的桌子是:

    table

    我编写的sql代码是:

    select RowID, start_contract, end_contract from table
    
    open the_cursor
    
    fetch next from the_cursor into @id
    
    while @@FETCH_STATUS = 0
    begin 
        select
            DATEDIFF(DAY, (select end_contract from table where RowID = @id-1), 
                          (select start_contract from t where RowID = @id)) AS [Difference]
    
            if (select RowID from t) = 1
                break
            else 
                continue
    
        fetch next from the_cursor into @id
    end
    
    close the_cursor
    deallocate the_cursor
    

    但我有个错误:

    cursorfetch:into列表中声明的变量数必须与所选列的变量数匹配。

    有人能帮我吗?

    非常感谢。

    1 回复  |  直到 6 年前
        1
  •  1
  •   DDS    6 年前

    试试这个:

    select DATEDIFF(DAY, T.end_contract T.start_contract) AS [Difference], T.personID
    from table T join table TT on TT.personID=t.personID
    where TT.rowID = T.rowID + 1