gpt4 book ai didi

sql - 使用postgresql的多选查询

转载 作者:行者123 更新时间:2023-11-29 13:22:55 25 4
gpt4 key购买 nike

我有两张 table

表_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

我尝试使用以下查询,但所有的数量都是重复的

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按 stock_p.method 分组,stock_p.stateenter code here

最佳答案

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 | |

9.4+ 使用 filter正如@a_horse 评论的那样。数据:

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');

关于sql - 使用postgresql的多选查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38639200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com