获取日期前后的列总和?

时间:2018-09-26 06:05:55

标签: sql postgresql

我需要从表格中获取日期前后的数量总和。

这是我尝试过的:

select location_id, t1.product_id, sum(t1.quantity) as open, 
       t2.product_id as t2_p,sum(t2.quantity) as current
from (select id, location_id, product_id, quantity
      from stock_history 
      where date::date<='2018-09-23') t1
FULL OUTER JOIN (select id, product_id, quantity
                 from stock_history 
                 where date::date>'2018-09-23') t2
    ON t1.product_id = t2.product_id
group by location_id, t1.product_id;

3 个答案:

答案 0 :(得分:2)

使用条件聚合

select location_id, product_id,
    sum(case when date::date>'2018-09-23' then quantity end) as current,
    sum(case when date::date<='2018-09-23' then quantity end) as open
from stock_history
group by location_id, product_id

答案 1 :(得分:2)

使用case表达式进行条件聚合:

select id, location_id, product_id,
       sum(case when date::date <= '2018-09-23' then quantity end),
       sum(case when date::date >  '2018-09-23' then quantity end)
from stock_history
group by id, location_id, product_id,

答案 2 :(得分:2)

我认为您不需要在那里参加。聚合的session(['your_data' => $your_data]); // save data so session $my_data = session('your_data'); // get data from session 子句可能会有所帮助:

FILTER