拆分和合并表的列的值

时间:2017-08-16 11:57:43

标签: sql postgresql

我的输出数据采用以下格式,

select 
trans_store_id as TRANS_WAREHOUSE_NAME, 
demand_store_id as DEMAND_WAREHOUSE_NAME, 
item_id as ITEM_NAME, 
NVL(transfer_qty,0) as TRANSFER_QTY 
from ORDER_DTL
WHERE gnum_isvalid=1




col1     col2    col3    col4
A        B       item1   500
A        C       item2   200
C        B       item1   300

我希望以下列格式获取数据,

col1     col2     col3     col4 
A        item1    500      0
B        item1    0        500
A        item2    200      0
C        item2    0        200
C        item1    300      0
B        item1    0        300

请原谅缺乏查询,因为我不知道从哪里开始。感谢。

1 个答案:

答案 0 :(得分:2)

只需使用union all

select col1, col3 as col2, col4 as col3, 0 as col4
from t
union all
select col2, col3, 0, col4
from t;

您已编辑了该问题。您可以使用CTE:

with t as (
      select trans_store_id, demand_store_id, 
             item_id, NVL(transfer_qty, 0) as transfer_qty 
      from ORDER_DTL
      where gnum_isvalid = 1
     )
select trans_store_id, item_id, transfer_qty, 0 as other_qty
from t
union all
select demand_store_id, item_id, 0, transfer_qty as other_qty
from t;