【问题标题】:How do I iterate over nested rows using a condition in SQL?如何使用 SQL 中的条件迭代嵌套行?
【发布时间】:2018-12-08 21:04:55
【问题描述】:

我想创建一个 FOR 循环的等价物。我在 SQL 中需要这个。我的目标是创建一个名为 Difference 的新列,它计算每行末尾和下一行开头之间的日期差(以天为单位)。本质上,我需要知道每个 personID 的合同是否有任何中断。 RowID 从 min 到 max 定义了与特定组织的合同,例如与一个组织的每个新合同都以 1 开头。

我的桌子是:

我写的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 列表中声明的变量数量必须与所选列的数量匹配。

有人可以帮帮我吗?

非常感谢。

【问题讨论】:

标签: sql while-loop


【解决方案1】:

试试这个:

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

【讨论】:

  • 谢谢,自加入效果很好。我不得不修改代码以通过 TT.rowID=T.rowID+1 而不是 where 添加连接,但它成功了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-21
  • 2017-03-22
  • 2013-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多