2017-04-26 28 views
0

我想實現我在代碼中作爲postgres查詢。 以下示例並不完全是我們正在嘗試執行的操作,但希望它顯示了我如何使用之前計算的行中的值。Postgres查詢:使用之前動態創建的列值在下

的試樣臺幫我證明我想要做的事:

test=# select * from test ; 
id | field1 | field2 | field3 | score 
----+--------+--------+--------+------- 
    1 |  1 |  3 |  2 | 1.25 
    2 |  1 |  -1 |  1 | 
    3 |  2 |  1 |  5 | 
    4 |  3 |  -2 |  4 | 

這裏正在進行的查詢:

select id, 
    coalesce (
      score, 
      case when lag_field3 = 2 then 0.25*(3*field1+field2) end 
    ) as new_score 
from (
    select id, field1, field2, field3, score, 
    lag (field3) over (order by id) as lag_field3 
    from test 
) inner1 ; 

它返回什麼,我想那麼遠,

id | new_score 
----+----------- 
    1 |  1.25 
    2 |  0.5 
    3 | 
    4 | 

查詢的下一次迭代:

select id, 
    coalesce (
      score, 
      case when lag_field3 = 2 then 0.25*(3*field1+field2) end, 
      case when field1 = 2 then 0.75 * lag (new_score) end 
    ) as new_score 
from (
select id, field1, field2, field3, score, 
    lag (field3) over (order by id) as lag_field3 
from test 
) inner1 ; 

的區別是:

case when field1 = 2 then 0.75 * lag (new_score) end 

我知道和明白爲什麼這是行不通的。

我已經計算出的字段作爲new_score的別名,當field1 = 2時,我想0.75 *前面的行new_score值。 我知道new_score是別名,不能使用。

有什麼方法可以完成這個嗎?我可以試着複製這個表達式,在它周圍加一個滯後,別名作爲別的東西,然後嘗試去處理,但那會變得非常混亂。

任何想法?

非常感謝。

+0

請提供的disred輸出最終查詢和創建表所需的查詢。 – pietrop

回答

0

Postgres讓您使用CASE語句中的窗口。可能你錯過了OVER (ORDER BY id)部分。您也可以定義不同的窗口,但不能將窗口與GROUP BY結合使用。此外,它不會讓你使用annidate窗口,所以你必須寫下一些子查詢或CTE。

這裏的查詢:

SELECT id, COALESCE(tmp_score, 
        CASE 
         WHEN field1 = 2 
          THEN 0.75 * LAG(tmp_score) OVER (ORDER BY id) 
          -- missing ELSE statement here 
        END 
      ) AS new_score 
FROM (
    SELECT id, field1, 
     COALESCE (
       score, 
       CASE 
        WHEN LAG(field3) OVER (ORDER BY id) = 2 
        THEN 0.25*(3*field1+field2) 
       END 
     ) AS tmp_score 
    FROM test 
) inner1 

創建和填充表的代碼:

CREATE TABLE test(
    id int, 
    field1 int, 
    field2 int, 
    field3 int, 
    score numeric 
); 

INSERT INTO test VALUES 
(1, 1, 3, 2, 1.25), 
(2, 1, -1, 1, NULL), 
(3, 2, 1, 5, NULL), 
(4, 3, -2, 4, NULL); 

查詢返回的輸出:

id | new_score 
----+----------- 
    1 |  1.25 
    2 |  0.50 
    3 | 0.3750 
    4 |   
+0

感謝您的回覆,我嘗試過,但沒有奏效......問題在於'new_score'是別名: 錯誤:列「new_score」不存在 LINE 5:CASE when field1 = 2 THEN 0.75 * LAG(new_score)... – David

+0

立即嘗試。順便說一下,它不是很清楚你想要做什麼。你加入的第二個滯後是否是聯合的一部分? – pietrop

+0

它不應該給你任何語法錯誤..請刷新瀏覽器頁面。 – pietrop