0

我有以下表结构,

客户信息

   cust_id
   cust_name

账单信息

    bill_id
    cust_id
    bill_amount
    bill_date

付费信息

    paid_id
    bill_id
    paid_amount  
    paid_date

现在我的输出应该显示两个日期之间的记录(2013 年 1 月 1 日至 2013 年 2 月 1 日)bill_dates,如下所示,

 cust_name | bill_id | bill_amount | tpaid_amount | bill_date | balance

tpaid_amount为特定 bill_id 支付的总金额在哪里

例如,

  • 对于账单 ID abcd,bill_amount 为 10000,用户支付 2000 一次和 3000 次

  • 意味着,paid_info 表包含两个相同的 bill_id 条目

    bill_id | paid_amount
    abcd         2000
    abcd         3000
    

所以,tpaid_amount = 2000 + 3000 = 5000balance = 10000 - tpaid_amount = 10000 - 5000 = 5000

有没有办法用单个查询(内部连接)来做到这一点?

4

2 回答 2

1

您想加入这 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 教程中。

希望我已经正确理解了这一点,并且这对您有所帮助。

于 2013-07-08T20:45:41.160 回答
1

这可以解决问题;

select
    cust_name,
    bill_id,
    bill_amount,
    sum(paid_amount),
    bill_date,
    bill_amount - sum(paid_amount)
from
    cust_info
    left outer join bill_info
        left outer join paid_info
        on bill_info.bill_id=paid_info.bill_id
    on cust_info.cust_id=bill_info.cust_id
where
    bill_info.bill_date between X and Y
group by
    cust_name,
    bill_id,
    bill_amount,
    bill_date
于 2013-07-08T20:46:33.460 回答