postgres查找同一列编号之间的差异

时间:2019-06-18 20:07:48

标签: sql postgresql

我有一个像下面的桌子

| date       | key | value |   |
|------------|-----|-------|---|
| 01-01-2009 | a   | 25    |   |
| 01-01-2009  | b   | 25    |   |
| 01-01-2009  | c   | 10    |   |

我正在尝试提出一个查询,该查询将允许我每天进行(a+b)-c次操作,但是我的联接正在执行此操作(a+b+c)-c

with total as (
select
    sum(value),
    date
from
    A
where
    key in ('a',
    'b')
group by
    date ) 
select
    sum(total.sum) as a, sum(A.value) as b,
    sum(total.sum) - sum(A.value) as value,
        A.date
    from
        A
    join total on
        total.date = A.date
    where
        A.key = 'c'
    group by
        A.date

这给了我50的值(应该是40)-我的C值在连接过程中作为总表的一部分被计算了

我在做什么错了?

2 个答案:

答案 0 :(得分:3)

简单地进行条件聚合怎么样?

select date,
       sum(case when key in ('a', 'b') then value 
                when key in ('c') then - value
           end) as daily_calc
from a
group by date;

join对于这种计算似乎不太有用。

答案 1 :(得分:2)

您可以连接三个表表达式,如下所示:

select
  a.date,
  (a.value + b.value) - c.value
from (select * from A where key = 'a') a
join (select * from A where key = 'b') b on b.date = a.date
join (select * from A where key = 'c') c on c.date = a.date