2011-07-08 18 views
4

このクエリを開始する方法もわかりません。連続していないユーザーのレコードを見つけよう

私は次の列とデータを持つテーブルを持っている:

User BeginMile EndMile 
1   1  5 
1   5  6 
1   6  20 
1   20  25 
1   25  29 
2   1   9 
2   15  20 
3   1   2 
3   6   10 
3   10  12 

私は前のレコードのEndMileから、次のレコードのBeginMileに、各ユーザのギャップがある場所を最初に見つける必要があります。私はその後、各ユーザーのギャップが発生する前後のレコードを返す必要があります。

前のデータの例では、私は以下返さたい:

User PrevBeginMile PrevEndMile AfterBeginMile AfterEndMile Gap 
2   1    9    15   20   6 
3   1    2    6   10   4 

はどのようにこれを行うことができますか?

+3

あなたはどのデータベースを使用していますか? –

+0

BeginDateとEndDate? BeginMileとEndMileを意味しますか? –

+0

SQL 2005 – mameesh

答えて

3

あなたはSQL 2005にしている考えると、これは動作するはずです:

DECLARE @Runners TABLE (Id INT, BeginMile INT, EndMile INT) 

INSERT INTO @Runners VALUES (1,1,5) 
INSERT INTO @Runners VALUES (1,5,6) 
INSERT INTO @Runners VALUES (1,6,20) 
INSERT INTO @Runners VALUES (1,20,25) 
INSERT INTO @Runners VALUES (1,25,29) 
INSERT INTO @Runners VALUES (2,1,9) 
INSERT INTO @Runners VALUES (2,15,20) 
INSERT INTO @Runners VALUES (3,1,2) 
INSERT INTO @Runners VALUES (3,6,10) 
INSERT INTO @Runners VALUES (3,10,12) 

WITH OrderedUsers AS (
    SELECT * 
    , ROW_NUMBER() OVER (PARTITION BY Id ORDER BY BeginMile) RowNum 
    FROM @Runners 
) 

SELECT a.Id [User] 
, a.BeginMile PrevBeginMile 
, a.EndMile PrevEndMile 
, b.BeginMile AfterBeginMile 
, b.EndMile AfterEndMile 
, b.BeginMile - a.EndMile Gap 
FROM OrderedUsers a 
JOIN OrderedUsers b 
ON a.Id = b.Id 
AND a.EndMile <> b.BeginMile 
AND a.RowNum = b.RowNum - 1 
RowNumber関数を(使用した以外は
+1

私は2つのサブクエリをCTEに置き換えています... ;; WITH ordered_table AS()SELECT blah FROM ordered_table INNER JOIN ordered_table AS b ON blah- de-blah' – MatBailie

+0

@Dems - 良い提案。更新しました。 –

0

)[他の回答のように]、あなたが使用することができます...

SELECT 
    [current].User, 
    [current].BeginMile     AS [PrevBeginMile], 
    [current].EndMile      AS [PrevEndMile], 
    [next].BeginMile      AS [AfterBeginMile], 
    [next].EndMile      AS [AfterEndMile], 
    [next].BeginMile - [current].EndMile AS [Gap] 
FROM 
    myTable AS [current] 
CROSS APPLY 
    (SELECT TOP 1 * FROM myTable WHERE user = [current].User AND BeginMile > [current].BeginMile ORDER BY BeginMile ASC) AS [next] 
WHERE 
[current].EndMile <> [next].BeginMile 

か多分...

FROM 
    myTable AS [current] 
INNER JOIN 
    myTable AS [next] 
    ON [next].BeginMile != [current].EndMile 
    AND [next].BeginMile = (
          SELECT 
           MIN(BeginMile) 
          FROM 
           myTable 
          WHERE 
           user = [current].User 
           AND BeginMile > [current].BeginMile 
          ) 
0

どの程度

WITH acte(user,beginmile,endmile) AS 
(
SELECT user,start,end 
ROW_NUMBER() OVER(PARTITION BY user ORDER BY START ASC) rownum 
FROM mytable 
) 
SELECT base.user,base.beginmile,base.endmile,base.BeginMile - lead.EndMile Gap 
FROM acte base 
LEFT JOIN acte lead on base.id=lead.id AND base.rownum=lead.rownum-1 
WHERE base.BeginMile - lead.EndMile > 0 
関連する問題