2012-05-02 46 views
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 

任何援助,高度赞赏

+5

你有表示你的公司的日历表“工作日”?否则,如果前一天是圣诞节,公司假期等,您将不得不编写各种例外情况。您希望的结果似乎完全忽略了您的日期之间有非工作日。我很困惑。 –

+0

要添加到@AaronBertrand的评论中,您至少需要一个包含假期和某种功能的表格来计算工作日。 – Taryn

回答

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 
+0

虽然这是上面的“结果”似乎表明OP要作为输出,但包含“工作日”似乎意味着在周六/周日的日子里需要考虑一些问题(不必介意任何假期或可能会涉及其他“非工作日”)。 –

+0

我不认为这回答了这个问题。你没有考虑到他们想要工作日,而不是日子之间的差异。 – Taryn

+0

他在哪里写关于工作日的任何事情?我看不到? – pkmiec