按日期汇总值,两个表

时间:2019-04-24 11:43:55

标签: sql postgresql

我在tab1和tab2中有两个表,目标是将tab2中所有给定id值的所有出现的值相加并显示在日期旁边;

我的第一个tab1看上去

+----+
| id |
+----+
| A  |
| B  |
| C  |
| D  |
+----+

第二个tab2看起来:

  +----+-----+-------+------------+
| in | out | value |    date    |
+----+-----+-------+------------+
| A  |     |    10 | 2019-05-06 |
| A  |     |   100 | 2019-05-11 |
| D  | C   |   100 | 2019-06-11 |
|    | A   |    50 | 2019-07-15 |
| C  |     |    11 | 2019-07-28 |
+----+-----+-------+------------+

例如,我想获得ID A:

+-----+------------+
| sum |    date    |
+-----+------------+
|  10 | 2019-05-06 |
| 110 | 2019-05-11 |
|  60 | 2019-07-15 |
+-----+------------+

有什么想法吗?我只能总结到给定的日期

3 个答案:

答案 0 :(得分:0)

使用窗口功能sum()

 select sum(value)over(partition by "in" order by date ) as s,date
 from table

答案 1 :(得分:0)

您似乎想要累积的总和:

select date, value,
       sum(value) over (partition by coalesce(in, out)
                        order by (case when "in" is not null then value else - value end)
                       ) as value_sum
from tab2 t
where coalesce("in", "out") = 'A'
order by date;

您可以使用子查询或横向联接来简化操作:

select t.date, v.signed_value,
       sum(value) over (partition by v.id
                        order by v.signed_value
                       ) as value_sum
from tab2 t cross join lateral
     (values (coalesce("in", "out"),
              (case when "in" is not null then value else - value end)
             )
     ) v(id, signed_value
where v.id = 'A'
order by t.date;

编辑:

如果可以同时输入和输出:

select date, value,
       sum(value) over (partition by coalesce(in, out)
                        order by (case when "in" is not null then value else - value end)
                       ) as value_sum
from tab2 t
where coalesce("in", "out") = 'A'
order by date;

您可以使用子查询或横向联接来简化操作:

select t.date, v.signed_value,
       sum(value) over (partition by v.id
                        order by v.signed_value
                       ) as value_sum
from tab2 t cross join lateral
     (values ("in", value), ("out", -value)),
     ) v(id, signed_value
where v.id = 'A'
order by t.date;

答案 2 :(得分:0)

对列值进行条件求和:

select
  (
    select sum(
      case when "in" = 'A' then 1 else - 1 end * value
    ) 
    from tab2 
    where 'A' in ("in", out) and 
    date <= t2.date
  ) sum, 
  date
from tab2 t2
where 'A' in (t2."in", t2.out) 

请参见demo
结果:

| sum | date       |
| --- |----------- |
| 10  | 2019-05-06 |
| 110 | 2019-05-11 |
| 60  | 2019-07-15 |