【问题标题】:Multiple select query using postgresql使用 postgresql 进行多选查询
【发布时间】:2016-07-28 14:21:49
【问题描述】:

我有两张桌子

table_a

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

table_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.state 分组在此处输入代码

【问题讨论】:

  • 感谢更新...
  • 在我看来,您在这里尝试做两件不同的事情。获取您想要的数据很容易,这是两个表的直接连接。更难的是您对数据所做的调整。这通常最好在不同的工具中完成。顺便说一句,查询似乎与表不匹配。

标签: sql postgresql


【解决方案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 |          |                   

9.4+ 使用 @a_horse 评论的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');

【讨论】:

  • 或者:sum(sm.qty) filter (where t1.date = current_date) as today
  • 您好,感谢重播。我确实尝试过,但它的显示数量在所有列中都是 0。
  • @user5668640 为我工作。用数据检查更新问题。
猜你喜欢
  • 1970-01-01
  • 2013-12-20
  • 2014-11-05
  • 2017-06-23
  • 1970-01-01
  • 2017-04-03
  • 2015-04-14
  • 2022-01-21
  • 2021-12-21
相关资源
最近更新 更多