您想加入这 3 个表,然后按账单 ID 和其他相关数据对它们进行分组,就像这样。
-- the select line, as well as getting your columns to display, is where you'll work
-- out your computed columns, or what are called aggregate functions, such as tpaid and balance
SELECT c.cust_name, p.bill_id, b.bill_amount, SUM(p.paid_amount) AS tpaid, b.bill_date, b.bill_amount - SUM(p.paid_amount) AS balance
-- joining up the 3 tables here on the id columns that point to the other tables
FROM cust_info c INNER JOIN bill_info b ON c.cust_id = b.cust_id
INNER JOIN paid_info p ON p.bill_id = b.bill_id
-- between pretty much does what it says
WHERE b.bill_date BETWEEN '2013-01-01' AND '2013-02-01'
-- in group by, we not only need to join rows together based on which bill they're for
-- (bill_id), but also any column we want to select in SELECT.
GROUP BY c.cust_name, p.bill_id, b.bill_amount, b.bill_date
group by 的快速概述:它会将您的结果集和 smoosh 行放在一起,具体取决于它们在您提供的列中具有相同数据的位置。由于每张账单都有相同的客户名称、金额、日期等,我们可以按照这些以及账单 ID 进行分组,我们将获得每张账单的记录。但是,如果我们想按 p.paid_amount 对其进行分组,因为每次付款都会有不同的付款(可能),您将获得每次付款的记录,而不是每张账单的记录,这不是您的记录我想要。一旦 group by 将这些行平滑在一起,您就可以运行聚合函数,例如 SUM(column)。在此示例中,SUM(p.paid_amount) 将具有该 bill_id 的所有付款相加,以计算已支付的金额。欲了解更多信息,请查看 W3Schools关于 group by 的章节在他们的 SQL 教程中。
希望我已经正确理解了这一点,并且这对您有所帮助。