2015-04-04 52 views
1

問題1SQL:分組上連續記錄第2部分

我有以下的表,其通過1示出了每一個以1周小時的間隔

 
Id EntityID EntityName LocationID   Timex delta 
1 1   Mickey  Club house   0300 1 
2 1   Mickey  Club house   0400 1 
3 1   Mickey  Park    0500 2 
4 1   Mickey  Minnies Boutique 0600 3 
5 1   Mickey  Minnies Boutique 0700 3 
6 1   Mickey  Club house   0800 4 
7 1   Mickey  Club house   0900 4 
8 1   Mickey  Park    1000 5 
9 1   Mickey  Club house   1100 6 

增量遞增的人的位置時間的位置變化。 我想按照下面的示例返回按delta分組的聚合。

 
EntityName LocationID   StartTime EndTime 
Mickey  Club house   0300  0500 
Mickey  Park    0500  0600 
Mickey  Minnies Boutique 0600  0800 
Mickey  Club house   0800  1000 
Mickey  Park    1000  1100 
Mickey  Club house   1100  1200 

我使用的是截斷並從這裏適應以下查詢 SQL: Group By on Consecutive Records (工作正常):

select 
    min(timex) as start_date 
    ,end_date 
    ,entityid 
    ,entityname 
    ,locationid 
    ,delta 
from 
    (
    select 
     s1.timex 
     ,( 
     select 
      max(timex) 
     from 
      [locationreport2] s2 
     where 
      s2.entityid = s1.entityid 
      and s2.delta = s1.delta 
      and not exists 
       (
       select 
        null 
       from 
        [dbo].[locationreport2] s3 
       where 
        s3.timex < s2.timex 
        and s3.timex > s1.timex 
        and s3.entityid <> s1.entityid 
        and s3.entityname <> s1.entityname 
        and s3.delta <> s1.delta 
       ) 
      ) as end_date 
    , s1.entityid 
    , s1.entityname 
    , s1.locationid 
    , s1.delta 
from 
    [dbo].[locationreport2] s1 
) Result 

group by 
    end_date 
    , entityid 
    , entityname 
    , locationid 
    , delta 
order by 
    1 asc 

但是我想不使用增量(它需要努力計算並填充它);相反,我想知道是否有任何方式來計算它的一部分/同時運行查詢。

我不介意使用視圖。

問題2

我有以下表,表示每隔1小時

 
Id EntityID EntityName LocationID Timex Delta 
1 1   Mickey  Club house 0900 1 
2 1   Mickey  Club house 1000 1 
3 1   Mickey  Park  1100 2 
4 2   Donald  Club house 0900 1 
5 2   Donald  Park  1000 2 
6 2   Donald  Park  1100 2 
7 3   Goofy  Park  0900 1 
8 3   Goofy  Club house 1000 2 
9 3   Goofy  Park  1100 3 

我想返回的人,位置分組聚集不同的人的位置。 例如

 
EntityID EntityName LocationID StartTime EndTime 
1   Mickey  Club house 0900 1100 
1   Mickey  Park  1100 1200 
2   Donald  Club house 0900 1000 
2   Donald  Park  1000 1200 
3   Goofy  Park  0900 1000 
3   Goofy  Club house 1000 1100 
3   Goofy  Park  1100 1200 

,我需要上面的查詢(問題1)什麼修改?

+0

您正在使用哪個版本的SQL Server? – jpw 2015-04-04 22:30:17

+0

SQL Server 2012 – 2015-04-06 04:32:25

回答

0

聽起來就像分析函數的一個例子。您需要將1小時添加到EndTime,但這將取決於數據類型。

SELECT EntityName, LocationID, StartTime, EndTime 
    FROM (SELECT EntityName, LocationID 
      ,MIN(Timex) OVER (PARTITION BY EntityID, delta ORDER BY delta) AS StartTime 
      ,MAX(Timex) OVER (PARTITION BY EntityID, delta ORDER BY delta) AS EndTime 
     FROM locationreport2 
    ) x 
    GROUP BY EntityName, LocationID, StartTime, EndTime 
    ORDER BY EntityName, StartTime 
+0

謝謝你ronin。這工作得很好。 – 2015-04-06 04:48:53