简体   繁体   English

sql联接查询多个表

[英]sql join query for multiple tables

I have following tables structure, 我有以下表格结构,

cust_info: cust_info:

  cust_id   cust_name
  1           nikhil
  2           sam

bill_info: bill_info:

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

paid_info: paid_info:

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

now my output should display sum of bill made by customer and total amount paid by that customer and balance amount 现在我的输出应显示客户的帐单总和,该客户支付的总金额以及余额

output 输出

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

where, for example, for cust_id = 2, 例如,对于cust_id = 2,

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

what is convenient way to do this in sql? 什么是方便的方法来做到这一点在SQL? any sample query? 任何样本查询?

here's what i've already tried 这是我已经尝试过的

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;
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 演示

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
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM