2016-10-21 121 views
1

我有點卡在一個項目,並想知道你們都會嘗試接下來。我試圖創建SQL代碼,將輸出下面的示例表的change_value字段中的值。順序案例陳述

id | sequence | event_type | change_value 
1 |  1 |  a  |  0 
1 |  2 |  b  |  1 
1 |  3 |  a  |  1 
1 |  4 |  b  |  1 
2 |  1 |  a  |  0 
2 |  2 |  b  |  1 
2 |  3 |  b  |  0 
2 |  4 |  b  |  0 
3 |  1 |  a  |  0 
3 |  2 |  a  |  0 
3 |  3 |  a  |  0 
3 |  4 |  a  |  0 

對於每一行,該值僅是0或1的邏輯如下:

IF `id` in the current row = `id` in the previous row; 
AND `sequence` in the current row > `sequence` in the previous row; 
AND `event_type` in the current row <> `event_type` in the previous row; 
THEN 1 
ELSE 0 

回答

0

我會去與left join

select t.*, 
     (case when tprev.event_type is null then 0 
      when tprev.event_type = t.event_type then 0 
      else 1 
     end) as change_value 
from t left join 
    t tprev 
    on tprev.id = t.id and 
     tprev.sequence = t.sequence - 1; 

這將作爲只要序列號沒有空位。

基本上有兩種方法。一種方法是一個複雜的查詢(比如說一個相關的子查詢)來獲得前面的結果。另一種是使用變量(另一種形式的複雜查詢)。以上比這些更簡單。更重要的是,它可以利用(id, sequence, event_type)的性能指標。

+0

我想OP的意思是'當tprev.event_type!= t.event_type然後1' –

+0

感謝您的快速回復。這是解決這個問題的好方法! – wentworth

+0

@JuanCarlosOropeza。 。 。謝謝。 –