我有一个带有主键customer_invoice_header的发票标题表cust_inv_id

然后有一个详细记录表customer_invoice_item和字段customer_invoice_header_id

每个标题都有很多行,这些行保存在customer_invoice_item表中。

我想编写一个sql以获取所有标头并显示记录详细信息的总和。我怎么做?

我写:

SELECT cih.cust_inv_id, sum(cii.amount) as records_total
FROM customer_invoice_header cih LEFT JOIN customer_invoice_item cii
ON cih.cust_inv_id = cii.customer_invoice_header_id


但是它仅返回一条记录。即使有10个标头记录。

劝告。

最佳答案

在查询末尾添加group by子句,例如:

SELECT cih.cust_inv_id, sum(cii.amount) as records_total
FROM customer_invoice_header cih LEFT JOIN customer_invoice_item cii
ON cih.cust_inv_id = cii.customer_invoice_header_id
GROUP BY cih.cust_inv_id

09-06 02:40