2017-09-12 3 views
1

T-SQLの選択クエリを使用してこの結果を達成する方法。 は、このサンプルテーブルを考える:T-SQL先行するグループ/条件の結果行を計算する場合に選択します。

create table sample (a int, b int) 

    insert into sample values (999, 10) 
    insert into sample values (16, 11) 
    insert into sample values (10, 12) 
    insert into sample values (25, 13) 
    insert into sample values (999, 20) 
    insert into sample values (14, 12) 
    insert into sample values (90, 45) 
    insert into sample values (18, 34) 

私はこの出力を達成しようとしている:

a   b   result    
    ----------- ----------- ----------- 
    999   10   10 
    16   11   10 
    10   12   10 
    25   13   10 
    999   20   20 
    14   12   20 
    90   45   20 
    18   34   20 

ルールは非常に簡単です:列は「」999結果の特別値を持っている場合( 'a'の値が再び999でない限り)その行とそれに続く行は列 'b'の値になります。最初のレコードが列 'a'に999を持つとします。

可能であれば、ストアドプロシージャや関数を使用せずにselectクエリを実装する方法を教えてください。

ありがとうございます。

あなたが順序を指定する列を追加する場合は、あなたがやりたいことができAntónioの

+2

SQL Serverには、「次」の行の概念がありません。 SQLテーブルは、順序付けられていないセットを表します。 –

答えて

1

あなたはidカラムを持っている必要があります

select cn.id, cn.a 
    , (select top (1) b from sample where sample.id <= cn.id and a = 999 order by id desc) 
from sample as cn 
order by id 
+0

ありがとう@Paparazzi –

2

create table sample (
    id int identity(1, 1), 
    a int, 
    b int 
); 

次に、あなたが最新である「999」のバージョンを見つけることによって、あなたがやりたいことができますその値をコピーします。ここでは、ウィンドウ関数を使用する方法である:

select a, b, max(case when a = 999 then b end) over (partition by id_999) as result 
from (select s.*, 
      max(case when a = 999 then id end) over (order by id) as id_999 
     from sample s 
    ) s; 
+0

@GordonLinoffありがとう、私はあなたの良いアイデアを参照してください、それはほぼ完璧です。ただし、max(b)を使用すると期待される出力とは異なる結果になります。列 'result'の値は13と45です(各グループの最大値、最初の値は10と20です)。 –

+1

@AntónioGonçalvesそれでは、「ケース」も必要なので、「999」の値は割り当てられた値です –

+0

ありがとう、@パパラッチが提供するソリューションもチェックしてください。 –

関連する問題