2013-04-18 47 views
1

我有一個表如下。我想根據以下來計算日期的差異(以秒爲單位)連續的行之間:計算除連續日期以外的所有行的差異?

  • 如果日期超過每天不同,那麼我們繼續前進,並計算差異
  • 如果日期相差超過一天,第二天有84600的連續天數,那麼我想先結合日期後纔會有差異

我目前正在做一個自聯接來處理第一個但我不確定是否有處理第二種情況的好方法。任何建議?

下面也給出了一個例子:

CREATE TABLE #TEMP(Person VARCHAR(100), StartTime Datetime, TotalSeconds INT) 


INSERT INTO #TEMP VALUES('A', '2013-02-20', 49800); -- We want to take the difference with the next row in this case 
INSERT INTO #TEMP VALUES('A', '2013-02-25', 3000); -- Before taking the difference, I want to first merge the next four rows because 5th March is followed by three days with the value 86400 
INSERT INTO #TEMP VALUES('A', '2013-03-05', 2100); 
INSERT INTO #TEMP VALUES('A', '2013-03-06', 86400); 
INSERT INTO #TEMP VALUES('A', '2013-03-07', 86400); 
INSERT INTO #TEMP VALUES('A', '2013-03-08', 86400); 
INSERT INTO #TEMP VALUES('A', '2013-03-09', 17100); 
INSERT INTO #TEMP VALUES('B', '2012-04-24', 22500); 
INSERT INTO #TEMP VALUES('B', '2012-04-26', 600); 
INSERT INTO #TEMP VALUES('B', '2012-04-27', 10500); 
INSERT INTO #TEMP VALUES('B', '2012-04-29', 41400); 
INSERT INTO #TEMP VALUES('B', '2012-05-04', 86100); 


SELECT * 
FROM #TEMP 

DROP TABLE #TEMP 

回答

2

以下處理第二種情況:

select Person, MIN(StartTime) as StartTime, MAX(StartTime) as maxStartTime 
from (SELECT *, 
      dateadd(d, - ROW_NUMBER() over (partition by person order by StartTime), StartTime) as thegroup 
     FROM #TEMP t 
    ) t 
group by Person, thegroup 

它組的所有對一個人的時間段,連續用日期摺疊成一個單一的時間段(開始和結束時間)。訣竅是分配一個序列號,使用row_number(),然後從StartTime獲取差異。這種差異對於一組連續日期是恆定的 - 因此外部group by

您可以使用with語句將其放入您的查詢中,然後獲得您在連續行之間所需的區別。

+0

+1 This is magic!謝謝。 – Legend