2

有人可以帮我解决这个令人困惑的情况吗?我有一个在 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

非常感谢任何帮助

4

1 回答 1

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
于 2012-05-02T22:40:22.293 回答