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