我有一個名爲payment_info的表,並帶有以下記錄。postgresql - 將單行更改爲多行
paymentid | customercode | previousbalance | paymentamount | remainingbalance
-----------------------------------------------------------------------------
PID0001 | CUST024 | 10000 | 2500 | 7500
PID0002 | CUST031 | 8500 | 3500 | 5000
PID0003 | CUST005 | 12000 | 1500 | 10500
然後,我想要的是創建一個3行上述表中的每行。 我希望我的結果看起來像這樣。
Payment Group | Payment Line Item | Payment ID | Customer Code | Type | Amount
--------------------------------------------------------------------------------------------------
1 | 1 | PID0001 | CUST024 | PREVIOUS BALANCE | 10000.00
1 | 2 | | | PAYMENT AMOUNT | 2500.00
1 | 3 | | | REMAINING BALANCE | 7500.00
2 | 1 | PID0002 | CUST031 | PREVIOUS BALANCE | 8500.00
2 | 2 | | | PAYMENT AMOUNT | 3500.00
2 | 3 | | | REMAINING BALANCE | 5000.00
3 | 1 | PID0003 | CUST005 | PREVIOUS BALANCE | 12000.00
3 | 2 | | | PAYMENT AMOUNT | 1500.00
3 | 3 | | | REMAINING BALANCE | 10500.00
這是我開始的查詢。但它沒有返回與上面相同的結果。
select row_number() over() as id,paymentid,customercode,'PREVIOUS BALANCE' as type,previousbalance from payment_info
union
select row_number() over() as id,'','','PAYMENT AMOUNT' as type,paymentamount from payment_info
union
select row_number() over() as id,'','','REMAINING BALANCE' as type,remainingbalance from payment_info
有沒有其他方法,我不會使用UNION關鍵字?因爲在真正的表格中,我將使用30多列,查詢數千條記錄。
我也不知道如何從付款組(每個付款ID)和付款行項目(每個組)創建自動生成號碼(ID)。
感謝
使用** UNION ALL **,它以低於UNION的成本自行返回所有行。另外:不能保證** row_number()over()**會產生所需的排序 - 使用EXPLICIT命令來保證排序。另見:http://stackoverflow.com/questions/1128737/unpivot-and-postgresql –
我可以添加你的'支付組'號碼:) – flutter
按要求添加空格。 – flutter