繁体   English   中英

如何使用PostgreSQL显示数据库查询中的记录

[英]how to show record in database query using postgresql

我有下表。

date       | ref# | received_qty | issued_qty | remarks
----------------------------------------------------
2017-07-01 |112   | 5            | 0          | order
2017-07-01 |113   | 3            | 0          | order
2017-07-02 |112   | 0            | 4          | issue
2017-07-02 |112   | 2            | 0          | order

我需要在不同的列中按日期显示这样的数据。

date      | ref# | received_qty | issued
--------------------------------------------------------
2017-07-01| 112  | 5            | 0
2017-07-01| 113  | 3            | 0
2017-07-02| 112  | 4            | 2    

您可以使用带有hading子句和union all聚合来组合两个select语句,如下所示:

with tab(date, ref, received_qty, issued_qty, remarks) as
(
 select '2017-07-01',112,5,0,'order' union all
 select '2017-07-01',113,3,0,'order' union all
 select '2017-07-02',112,0,4,'issue' union all
 select '2017-07-02',112,2,0,'order' 
)
select date, ref,
       sum(issued_qty) as received_qty,
       sum(received_qty) as issued_qty           
  from tab
 group by date, ref
 having min(remarks) = 'issue'
union all
select date, ref,
       sum(received_qty) as received_qty,
       sum(issued_qty) as issued_qty           
  from tab
 group by date, ref
 having min(remarks) = 'order'
 order by date, ref;

演示版

我怀疑您只是想要这样:

select date, ref, sum(received_qty) as received_qty, sum(issued_qty) as issued_qty
from tab
group by date, ref
order by date, ref;

请注意,这将返回:

date      | ref# | received_qty | issued
--------------------------------------------------------
2017-07-01| 112  | 5            | 0
2017-07-01| 113  | 3            | 0
2017-07-02| 112  | 2            | 4

这个结果比您拥有的更有意义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM