SQL - 如何逐项获取最终数量?

时间:2018-05-08 07:41:11

标签: sql database postgresql

我有书库表,如:

---------------------------------------------------------------------
|   BOOK_ID     |   WAREHOUSE   |   UNITS   |   QTY_IN  |   QTY_OUT |
---------------------------------------------------------------------       
|       1       |       W01     |   PCS     |     5     |     0     | 
---------------------------------------------------------------------
|       2       |       W02     |   BOX     |     1     |     0     |
---------------------------------------------------------------------
|       1       |       W01     |   PCS     |     20    |     0     |
---------------------------------------------------------------------
|       1       |       W01     |   BOX     |     2     |     0     |
---------------------------------------------------------------------
|       1       |       W01     |   PCS     |     0     |     2     |
---------------------------------------------------------------------

我想获得每本书籍的最终数量,例如:

  • for BOOK_ID 1 TOTAL QTY IS 2 BOX,23 PCS
  • for BOOK_ID 2 TOTAL QTY是1 BOX
  • 等......

这是我迄今为止尝试过的:

select BOOK_ID, UNITS, WAREHOUSE, sum(QTY_IN) as QTY_IN, sum(QTY_OUT) as QTY_OUT from 
(select BOOK_ID, UNITS, WAREHOUSE, QTY_IN, QTY_OUT
from BOOK_STOCK) d
group by BOOK_ID, UNITS, WAREHOUSE

请帮我如何分组并总结数量? 谢谢。

2 个答案:

答案 0 :(得分:2)

使用case表达式进行条件聚合:

select BOOK_ID,
       sum(case when units = 'BOX' then QTY_IN - QTY_OUT else 0 end) as QTY_BOX,
       sum(case when units = 'PCS' then QTY_IN - QTY_OUT else 0 end) as QTY_PCS
from BOOK_STOCK
group by BOOK_ID

答案 1 :(得分:0)

下面的代码应该为您提供帮助。

select BOX.book_id, BOX.TotalQty as BoxFinalQuantity, PCS.TotalQty as PCSFinalQuantity
from 
(
select book_id, units, sum(qty_in-qty_out) as TotalQty from #Books
where units like 'BOX'
group by book_id, units) BOX
full outer join (
select book_id, units, sum(qty_in-qty_out) as TotalQty from #Books
where units like 'PCS'
group by book_id, units) PCS ON BOX.book_id = Pcs.book_id

select BOX.book_id, BOX.TotalQty as BoxFinalQuantity, PCS.TotalQty as PCSFinalQuantity from ( select book_id, units, sum(qty_in-qty_out) as TotalQty from #Books where units like 'BOX' group by book_id, units) BOX full outer join ( select book_id, units, sum(qty_in-qty_out) as TotalQty from #Books where units like 'PCS' group by book_id, units) PCS ON BOX.book_id = Pcs.book_id