根据来自另一个字段的代码聚合字段中的多个值

时间:2012-02-13 20:54:23

标签: sql postgresql pivot aggregate-functions

我需要根据同一个表中另一个字段中的代码从表中的字段计算多个值。

该表位于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)

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;