2011-12-21 4 views
1

の間に差がある場合、私は、次の表を持っている:チェック二列

column_a column_b column_c column_d column_date 
1  test_1 test_1 type_1 11:00 
2  test_2 test_2 type_2 11:01 
3  test_3 test_6 type_2 11:02 
4  test_4 test_4 type_3 11:03 
5  test_2 test_6 type_2 11:04 
6  test_1 test_2 type_1 11:05 

Iはcolumn_d(タイプ)によってフィルタリングCOLUMN_Bとcolumn_cに別の値を持つ行チェックしなければなりません。私は自分のSQLスクリプトで最初の2行だけcolumn_dateで各タイプの順序で分析する必要があります。 カラムの1つ(column_b、column_cまたはcolumn_d)に2つのローが異なる場合は、最初のローの値を出力する必要があります(それ以外の場合はnull)。

は、私は次のような結果を期待上記の例では:

column_a column_b column_c column_d column_date 
5  test_2 null  type_2 11:04 
6  null  test_2 type_1 11:05 

私はMS SQL ServerのT-SQLを使用することができますが、2008年

答えて

3

それはあなたがcolumn_date列に使用するもの、データ型、私にとって明確ではありませんしかし、それは時間と仮定しましょう。

DECLARE @Table TABLE (
     column_a INT   , 
     column_b VARCHAR (128), 
     column_c VARCHAR (128), 
     column_d VARCHAR (128), 
     column_date [time]  ); 

    INSERT INTO @Table 
    VALUES 
    ('1', 'test_1', 'test_1', 'type_1', '11:00'), 
    ('2', 'test_2', 'test_2', 'type_2', '11:01'), 
    ('3', 'test_3', 'test_6', 'type_2', '11:02'), 
    ('4', 'test_4', 'test_4', 'type_3', '11:03'), 
    ('5', 'test_2', 'test_6', 'type_2', '11:04'), 
    ('6', 'test_1', 'test_2', 'type_1', '11:05'); 

    WITH  C 
    AS  (SELECT *, 
        ROW_NUMBER() OVER (PARTITION BY column_d ORDER BY column_date DESC) AS RN 
       FROM @Table), 
      ToCompare 
    AS  (SELECT * 
       FROM c 
       WHERE Rn < 3 
        AND EXISTS (SELECT * 
           FROM c AS C2 
           WHERE C.column_d = C2.column_d 
             AND Rn = 2)) 
    SELECT T.column_a, 
      NULLIF (T.column_b, T2.column_b) AS [column_b], 
      NULLIF (T.column_c, T2.column_c) AS [column_c], 
      T.column_d, 
      T.column_date 
    FROM  ToCompare AS T 
      INNER JOIN 
      ToCompare AS T2 
      ON T.column_d = T2.column_d 
    WHERE T.Rn = 1 
      AND T2.RN = 2 
    ORDER BY T.column_a; 
+0

こんにちはダレックス、たくさんありがとう!それでおしまい! :-) – bitsmuggler