sql连接查询多个表

时间:2013-07-12 18:56:59

标签: sql

我有以下表结构,

cust_info:

  cust_id   cust_name
  1           nikhil
  2           sam

bill_info:

 bill_id  cust_id   bill_amount 
    7         1     10000
    8         1     15000
    9         2     6000
    10        2     4000

paid_info:

   paid_id      cust_id  paid_amount  
      11         1        5000
      12         1        5000
      13         2        5000
      14         2        5000

现在我的输出应显示客户的账单总额和该客户支付的总金额以及余额

输出

  cust_id   total_bill   total_paid  balance
    1        25000         10000      15000
    2        10000          10000       0

其中, 例如, for cust_id = 2,

 total_bill= 10000 + 15000
 total_paid = 5000 + 5000
 balance = total_bill - total_paid

在sql中执行此操作的便捷方法是什么?任何样本查询?

这是我已经尝试过的东西

SELECT distinct c.cust_id
    , sum(b.bill_amount) as total_bill
    , SUM(p.paid_amt) AS totalpaid,sum(b.bill_amount) - SUM(p.paid_amt) AS balance 
FROM cust_info c 
INNER JOIN bill_info b ON c.cust_id = b.cust_id 
INNER JOIN paid_info p ON p.cust_id= b.cust_id group by p.cust_id;

3 个答案:

答案 0 :(得分:3)

SELECT 
    cust_info.cust_id,
    cust_name,
    bill_amount,
    paid_amount,
    bill_amount - paid_amount AS balance
FROM cust_info
INNER JOIN (
    SELECT cust_id, SUM(bill_amount) bill_amount
    FROM bill_info
    GROUP BY cust_id
) bill_info ON bill_info.cust_id = cust_info.cust_id
INNER JOIN (
    SELECT cust_id, SUM(paid_amount) paid_amount
    FROM paid_info
    GROUP BY cust_id
) paid_info ON paid_info.cust_id = cust_info.cust_id

demo

答案 1 :(得分:0)

SELECT c.cust_id,
       SUM(b.total_bill),
       SUM(p.total_paid),
       SUM(c.total_bill) - SUM(p.total_paid)
FROM
    cust_info c
    LEFT JOIN bill_info b ON (c.cust_id = b.cust_id)
    LEFT JOIN paid_info p ON (c.cust_id = p.party_id)
GROUP
    BY cust_info.cust_id

答案 2 :(得分:0)

SELECT DISTINCT cust_info.cust_id,
                sum(bill_amount) AS 'total_bill' ,
                sum(paid_amount) AS 'total paid' ,
                (SUM(bill_amount) - sum(paid_amount)) AS balance
FROM cust_info
INNER JOIN bill_info ON cust_info.cust_id = bill_info.cust_id
INNER JOIN paid_info ON cust_info.cust_id = paid_info.cust_id
GROUP BY cust_info.cust_id