SQL内部联接查询

时间:2013-07-08 20:34:11

标签: sql inner-join

我有以下表结构,

cust_info

   cust_id
   cust_name

bill_info

    bill_id
    cust_id
    bill_amount
    bill_date

paid_info

    paid_id
    bill_id
    paid_amount  
    paid_date

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

 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

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

2 个答案:

答案 0 :(得分: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(列)等聚合函数。在此示例中,SUM(p.paid_amount)总计了具有该bill_id的所有付款,以计算已支付的金额。有关详细信息,请参阅他们的SQL教程中的W3Schools chapter on group by

希望我能正确理解这一点,这对你有帮助。

答案 1 :(得分: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