SQL从子查询中获取一列作为逗号分隔的值

时间:2018-07-03 06:37:16

标签: sql database postgresql subquery

我的postresql中有这些表:-
1.付款方式(编号,编号,金额)
2.发票(编号,编号,金额)
和用于将付款金额分配给发票的invoice_payment表
3.InvoicePayment(id,payment_id,invoice_id,金额)
可以将单笔付款分配给许多发票。 现在我需要付款明细,但我也要有发票。此付款分配的发票编号。我正在做这样的事情:-

SELECT
    payments.number,
    payments.amount,
    (SELECT invoices.number from invoices INNER JOIN invoice_payments
     ON invoices.id = invoice_payments.invoice_id
     WHERE invoice_payments.payment_id = payments.id)
from payments

但是它给我的错误超过了子查询返回的一行。如何使每个付款行的发票号逗号分隔? 样本数据:-

Payment  
id  number  amount  
1  "Pay001" 100  
2 "Pay002" 150  
3 "Pay003" 150 
Invoice  
id number amount  
1 "INV001" 100  
2 "INV002" 200  
3 "INV003"  100  
InvoicePayment  
id payment_id invoice_id amount  
1    1          1          50  
2    1          2          50  
3    2          2          150  
4    3          1           50  
5    3          3          100  

Result:-  

payment_id payment_number amount invoices  
1          "Pay001"       100    "INV001, INV002"  
2          "Pay002"       150    "INV002"  
3          "Pay003"       150    "INV001, INV002"

2 个答案:

答案 0 :(得分:1)

您可以在postgres中使用string_agg函数来连接行,并以选定的分隔符分隔。

SELECT
    payments.number,
    payments.amount,
    (SELECT string_agg(invoices.number,',') from invoices INNER JOIN invoice_payments
     ON invoices.id = invoice_payments.invoice_id
     WHERE invoice_payments.payment_id = payments.id)
from payments

答案 1 :(得分:1)

尝试一下

SELECT
    payments.number,
    payments.amount,
    inv_p.inv_no
from payments p inner join (Select invoice_payments.payment_id, string_agg(invoices.number,',') as inv_no
                            From invoices inner join invoice_payments on (invoices.id = invoice_payments.invoice_id)
                            Group by invoice_payments.payment_id) inv_p on (p.id = inv_p.payment_id)