2016-09-21 60 views
0

MySQL Workbench 6.3。我有以下數據集。通過id和month獲取上一個值,第二個上一個值和第三個上一個值

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'嗎?我不明白這一行'(select date('2015-12-01')as curmon)params'params(temp table name?)和'date('2015-12-01')'的含義是什麼意思? – qqqwww

+0

'params'是一個基本的派生表,這是SQL中的一個基本構造。 'max()'只用於選擇符合條件的值。 –

相關問題