2015-06-26 60 views
0

我有這樣的輸入:差價日期

+-----+---------+-------+------------+------------+ 
| key | company | price | week_start | price_diff | 
+-----+---------+-------+------------+------------+ 
| 123 | xxx  | 15 | 02-06-2015 |   | 
| 456 | xxx  | 20 | 02-06-2015 |   | 
| 789 | yyy  | 30 | 02-06-2015 |   | 
| 122 | zzz  | 40 | 02-06-2015 |   | 
| 123 | xxx  | 50 | 09-06-2015 |   | 
| 456 | xxx  | 60 | 09-06-2015 |   | 
| 333 | yyy  | 70 | 09-06-2015 |   | 
+-----+---------+-------+------------+------------+ 

預期輸出:

更新列price_diff

+-----+---------+-------+------------+------------+ 
| key | company | price | week_start | price_diff | 
+-----+---------+-------+------------+------------+ 
| 123 | xxx  | 15 | 02-06-2015 |   | 
| 456 | xxx  | 20 | 02-06-2015 |   | 
| 789 | yyy  | 30 | 02-06-2015 |   | 
| 122 | zzz  | 40 | 02-06-2015 |   | 
| 123 | xxx  | 50 | 09-06-2015 |   35 | 
| 456 | xxx  | 60 | 09-06-2015 |   40 | 
| 333 | yyy  | 70 | 09-06-2015 |   | 
+-----+---------+-------+------------+------------+ 

company= 'xxx'key = 123我想利用價格差異根據week_start。從以上輸入爲company = 'xxx'key = 123,第二週有price = 50,第一週價格= 15。我需要用這兩個值的差異更新price_diff。

在此先感謝

+0

'y'呢?只有2個星期?他們總是喜歡02 --- 09 --- 16 ...或者可以有02 --- 04 --- 07 --- 10 --- 16 ...? –

+0

感謝您的回覆..我有很多個星期,它將總是像02 --- 09 --- 16 ..我想更新price_diff周到周和它的唯一公司='xxx' – Rajesh

回答

0

你應該着手的方法是做一個self-join,這意味着基於同一公司的日期和公司的ID之間1周差異與自身加入表。

在我的下面的查詢中,我還在KEY上添加了一個JOIN,因爲這個邏輯顯然會映射您的數據,但我不建議使用重複的KEY值,如果這個列應該包含唯一值(如果您'不使用複合鍵)。

但無論如何,這裏是你可以嘗試(假設你的表稱爲"prices")什麼:

SELECT p1.* 
    , p1.price - p2.price AS 'price_diff' 
FROM prices p1 
    LEFT JOIN prices p2 ON p1.company = p2.company 
     AND p2.week_start = p1.week_start - 7 * INTERVAL '1 day' 
     AND p1.KEY = p2.KEY 
ORDER BY p1.week_start, p1.company, p1.KEY 

此外,工作SQLFiddle樣本。

更新:

爲了更新price_diff列,根據我上面的查詢,你將不得不將其更改爲UPDATE,象下面這樣:

UPDATE prices 
    SET price_diff = p1.price - p2.price 
FROM prices p1 
    LEFT JOIN prices p2 ON p1.company = p2.company 
     AND p2.week_start = p1.week_start - 7 * INTERVAL '1 day' 
     AND p1.KEY = p2.KEY 
+0

感謝您的回覆..我想更新price_diff列 – Rajesh

+0

我在更新時遇到錯誤錯誤:目標表必須是等距鏈接謂詞的一部分..我使用的是Postgres – Rajesh

+0

@kr_kr您是否使用Amazon Redshift? –

0

你可以做到這一點窗函數:

WITH diff (key, company, week_start, price) AS (
    SELECT key, company, week_start, 
     price - lag(price) OVER (PARTITION BY key, company ORDER BY week_start) 
    FROM mytable) 
UPDATE mytable 
SET price_diff = diff.price 
FROM diff 
WHERE company = 'xxx' AND diff.company = 'xxx' 
    AND key = 123 AND diff.key = 123 
    AND week_start = diff.week_start; 
+0

您的查詢給我一個語法錯誤。 'diff.key = 123'之前有一個額外的撇號。 –

+0

啊,複製並粘貼錯誤,謝謝你。糾正。 – Patrick

+0

@帕特里克:感謝您的重播 – Rajesh

0
update mytable 
set price_diff = price - (
    select price 
    from mytable as t2 
    where 
     and t2.key = k1.key and t2.company = 'xxx' 
     and t2.week_start = mytable.week_start - 7 * INTERVAL '1 day' 
    ) 
where company = 'xxx' and price_diff is null