【发布时间】:2017-05-08 15:01:53
【问题描述】:
我有一个名为 payment_info 的表,其中包含以下记录。
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 order by 来保证正确排序。另见:stackoverflow.com/questions/1128737/unpivot-and-postgresql
-
我可以添加你的
payment group号码:) -
按要求添加了空格。
-
Whitespace文字版现在更好
标签: sql postgresql