使用postgresql进行多选查询

时间:2016-07-28 14:21:50

标签: sql postgresql

我有2张桌子

表-A

id  b_ref_id    qty
52  9            13
53  10           20
54  11           25

表-B

id  method       date                state
9   m1          28/07/16             confirmed
10  m1          29/07/16             done
11  m1          30/07/16             waiting

我的愿望输出

m1         today    tomorrow    day_after_tomorrow
waiting     13       0                 0
confirmed   0        20                0
done        0        0                 25

我尝试使用以下查询,但qty重复所有

select stock_p.method, stock_p.state, 
(select sm.qty
 from 
    table_a sm
    join table_b spo on (sm.b_ref_id=spo.id)
where
    to_char(spo.date,'YYYY-MM-DD')::date = current_date and ) today_qty,
(select sm.qty
from table_a sm
    join table_b spo on (sm.b_ref_id=spo.id)
where 
    to_char(spo.date,'YYYY-MM-DD')::date = (current_date + 1) ) tomorrow_qty,
(select sm.qty
from table_a sm
    join table_b spo on (sm.b_ref_id=spo.id)
    where
    to_char(spo.date,'YYYY-MM-DD')::date = (current_date + 2)) next_three_qty

这     table_a stock_m     在stock_m.b_ref_id = stock_p.id上加入table_b stock_p group by stock_p.method,stock_p.stateenter code here

1 个答案:

答案 0 :(得分:1)

select
    t1.method, t1.status,
    sum ((t1.min_date = current_date or null)::int * sm.product_qty) as today,
    sum ((t1.min_date = current_date + 1 or null)::int * sm.product_qty) as tomorrow,
    sum ((t1.min_date = current_date + 2 or null)::int * sm.product_qty) as day_after_tomorrow
from
    stock_move sm
    inner join
    table_1icking t1 on sm.picking_id = t1.id
group by t1.method, t1.status
;
 method |  status   | today | tomorrow | day_after_tomorrow 
--------+-----------+-------+----------+--------------------
 m1     | waiting   |       |          |                 25
 m1     | done      |       |       20 |                   
 m1     | confirmed |    13 |          |                   

由@a_horse评论使用9.4+使用filter。数据:

create table stock_move (id int, picking_id int, product_qty int);
insert into stock_move (id, picking_id, product_qty) values
(52,9,13), (53,10,20), (54,11,25);
set datestyle = 'dmy';
create table table_1icking (id int, method text, min_date date, status text);
insert into table_1icking (id, method, min_date, status) values
(9,'m1','28/07/16','confirmed'),
(10,'m1','29/07/16','done'),
(11,'m1','30/07/16','waiting');