2012-02-13 81 views
1

我需要根據同一個表的另一個字段中的代碼計算表中某個字段的多個值。根據來自另一個字段的代碼彙總來自某個字段的多個值

該表位於PostgreSQL 8.3數據庫中。

表:

cod_1 | cod_2 | date | cod_sum| import 
1  | 2 | 01/01/2012 |  a | 1.1 
1  | 2 | 01/01/2012 |  a | 1.2 
1  | 2 | 01/01/2012 |  b | 1.1 
1  | 2 | 01/01/2012 |  b | 1.1 
1  | 2 | 01/01/2012 |  c | 1.1 
1  | 2 | 01/01/2012 |  c | 1.1 

我需要的是這樣的:

cod_1 | cod_2 |date  |sum_import_a|sum_import_b|calc_import_abc(a+b-c) 
1  | 2 |01/01/2012| 2.3  | 2.2  | 2.3 (2.3+2.2-2.2) 

我希望你能伸出援助之手......

回答

0

隨着新window functions的PostgreSQL 8.4或更高版本),你甚至可以做,沒有子查詢:

SELECT cod_1, cod_2, date 
     , first_value(sum(import)) OVER w AS sum_import_a 
     , nth_value(sum(import), 2) OVER w AS sum_import_b 
     , first_value(sum(import)) OVER w 
     + nth_value(sum(import), 2) OVER w 
     - last_value(sum(import)) OVER w AS calc_import_abc 
FROM tbl 
GROUP BY 1, 2, 3, cod_sum 
WINDOW w AS (ORDER BY cod_sum 
      RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) 
LIMIT 1; 

爲了簡單起見,然而,(和PostgreSQL 8.3版本)我會做它像@Adrian演示,只是沒有邏輯錯誤:

SELECT cod_1, cod_2, date, sum_import_a, sum_import_b 
    , sum_import_a 
     + sum_import_b 
     - sum_import_c AS calc_import_abc 
FROM (
    SELECT cod_1, cod_2, date 
      , sum(CASE WHEN cod_sum = 'a' THEN import ELSE 0 END) sum_import_a 
      , sum(CASE WHEN cod_sum = 'b' THEN import ELSE 0 END) sum_import_b 
      , sum(CASE WHEN cod_sum = 'c' THEN import ELSE 0 END) sum_import_c 
    FROM tbl 
    GROUP BY 1, 2, 3 
    ) x; 
+0

Thx!它工作!我需要做一個更有說服力的測試,但我認爲只是我需要!非常感謝你... – bl4ckb1rd 2012-02-14 02:14:49

0

假設您的列集始終是相同的(關於值a,b和c),這裏是你需要的:

select 
    cod_1, cod_2, date, sum_import_a, sum_import_b, 
    sum_import_a + sum_import_b - sum_import_c as calc_import_abc 
from 
( 
    select cod_1, cod_2, date 
     sum(case cod_sum when 'a' then 1 else 0 end) sum_import_a, 
     sum(case cod_sum when 'b' then 1 else 0 end) sum_import_b, 
     sum(case cod_sum when 'c' then 1 else 0 end) sum_import_c 
    from YourTable 
    group by cod_1, cod_2, date 
) sel 
+0

謝謝!!!我使用由Erwin修改的代碼... – bl4ckb1rd 2012-02-14 02:15:56

相關問題