2016-09-21 10 views
0

MySQL Workbench 6.3。私は次のデータセットを持っています。IDと月によって最後の値、2番目の最後の値、最後の3番目の値を取得します。

id date  value 
36 12/1/2015 3174 
36 11/1/2015 3143 
36 10/1/2015 3112 
36 9/1/2015 3082 
36 8/1/2015 3052 
36 7/1/2015 3021 
36 6/1/2015 2990 
64 11/1/2015 3105 
64 10/1/2015 3074 
64 8/1/2015 3014 
64 7/1/2015 2983 
64 6/1/2015 2952 
65 12/1/2015 3414 
72 10/1/2015 3352 
72 9/1/2015 3322 
72 8/1/2015 3292 
72 7/1/2015 3261 
72 6/1/2015 3230 
72 5/1/2015 3198 
72 4/1/2015 3169 
72 3/1/2015 3139 
72 2/1/2015 3107 
72 1/1/2015 3079 

私が得ようとしているのは、IDでグループ化し、過去3か月の値を取得することです。 (未処理のデータにレコードがない場合は、日付と値をすべて保持してください) 次の表は、私が得たいものを表示する私のマニュアル出力です。どうもありがとうございます。

id current_month value1 1_month_before_current value2 2_month_before_current value3 3_month_before_current value3 
36 12/1/2015  3174 11/1/2015    3143 10/1/2015    3112 9/1/2015    3082 
64 null   null 11/1/2015    3105 10/1/2015    3074 null     null 
72 null   null null     null 10/1/2015    3352 9/1/2015    3322 
+0

どのRDMSおよび/またはバージョン? –

+0

MySQL Workbench 6.3 – qqqwww

答えて

0

ただ、条件付き集約を使用します。

select id, 
     max(case when date = '2015-12-01' then date end) as current_month, 
     max(case when date = '2015-12-01' then value end) as current_value, 
     max(case when date = '2015-11-01' then date end) as prev_month, 
     max(case when date = '2015-11-01' then value end) as prev_value, 
     max(case when date = '2015-10-01' then date end) as prev2_month, 
     max(case when date = '2015-10-01' then value end) as prev2_value, 
from t 
group by id; 

あなたは、日付を入力気に入らない場合:日付の最初にすべてでない場合は、

select id, 
     max(case when date = curmon then date end) as current_month, 
     max(case when date = curmon then value end) as current_value, 
     max(case when date = curmon - interval 1 month then date end) as prev_month, 
     max(case when date = curmon - interval 1 month then value end) as prev_value, 
     max(case when date = curmon - interval 2 month then date end) as prev2_month, 
     max(case when date = curmon - interval 2 month then value end) as prev2_value, 
from t cross join 
    (select date('2015-12-01') as curmon) params 
group by id; 

も月、case式の範囲ロジックを使用できます。

+0

ここで 'max'を使用する理由を知ることができますか?そして、私はこの行を理解していません('2015-12-01 'をcurmonとして選択)params' params(temp table name?)と 'date(' 2015-12-01 ')の意味は、 ? – qqqwww

+0

'params'は基本的な派生テーブルです。これはSQLの基本的な構文です。 'max()'は、条件に合った値を選択するためだけに使用されます。 –

関連する問題