如何计算结果集中上一行的工作日数?

时间:2012-05-02 22:22:33

标签: sql sql-server-2008 sql-server-2005

有人可以帮我解决这个令人困惑的情况吗?我在SQL Server 2008中生成了一个表。

Number  Date
------  ---------
22619   30/06/11
22617   01/07/11
22556   03/07/11
22556   03/07/11
22560   04/07/11
22560   05/07/11
22560   08/07/11
22561   07/07/11
22561   17/07/11
22564   09/07/11
22564   20/07/11

我希望从以前的角色中为每个号码生成相同的天数。

我想回复以下内容:

Number  Date        Days
------  ----------  ----
22619   30/06/11       0
22617   01/07/11       0
22556   03/07/11       0
22556   03/07/11       0
22560   04/07/11       0
22560   05/07/11       1
22560   08/07/11       3
22561   07/07/11       0
22561   17/07/11      10
22564   09/07/11       0
22564   20/07/11      11

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

我想你想要这个:

with data as (
    select number = 22619, date = convert(datetime, '20110630') union all
    select 22617, convert(datetime, '20110701') union all
    select 22556, convert(datetime, '20110703') union all
    select 22556, convert(datetime, '20110703') union all
    select 22560, convert(datetime, '20110704') union all
    select 22560, convert(datetime, '20110705') union all
    select 22560, convert(datetime, '20110708') union all
    select 22561, convert(datetime, '20110707') union all
    select 22561, convert(datetime, '20110717') union all
    select 22564, convert(datetime, '20110709') union all
    select 22564, convert(datetime, '20110720')
)
select next.number, next.date, days = isnull(DATEDIFF(dd, prev.date, next.date),0)
from (
    select *, sequence_no = ROW_NUMBER() OVER(PARTITION BY number ORDER BY date ASC)
    from data
) next
left join (
    select *, sequence_no = ROW_NUMBER() OVER(PARTITION BY number ORDER BY date ASC)
    from data
) prev
on prev.number = next.number
and prev.sequence_no + 1 = next.sequence_no