多表的sql联接查询
我有下面的表格结构 客户信息:多表的sql联接查询,sql,Sql,我有下面的表格结构 客户信息: cust_id cust_name 1 nikhil 2 sam 账单信息: bill_id cust_id bill_amount 7 1 10000 8 1 15000 9 2 6000 10 2 4000 付费信息: paid_id cust_id
cust_id cust_name
1 nikhil
2 sam
账单信息:
bill_id cust_id bill_amount
7 1 10000
8 1 15000
9 2 6000
10 2 4000
付费信息:
paid_id cust_id paid_amount
11 1 5000
12 1 5000
13 2 5000
14 2 5000
现在,我的输出应该显示客户的账单总额、该客户支付的总金额和余额
输出
在哪里,,
例如
对于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;
是的,有。In包括WHERE、AS、SUM、DIFF和JOIN。具体语法取决于您使用的数据库是MySQL、Oracle SQL、MSSQL、PostgreSQL等。选择不同的c.cust_id、sumb.bill_amount作为total_bill、SUMp.paid_amount作为totalpaid,sumb.bill_amount-sumb.paid_amount作为c.cust_id上的cust_info c内部联接bill_info b的余额=b.party_id内部联接p.cust_id上的paid_info p=b.cust_id按p.cust_id分组;我试过了是的,有。In包括WHERE、AS、SUM、DIFF和JOIN。具体语法取决于您使用的数据库是MySQL、Oracle SQL、MSSQL、PostgreSQL等。选择不同的c.cust_id、sumb.bill_amount作为total_bill、SUMp.paid_amount作为totalpaid,sumb.bill_amount-sumb.paid_amount作为c.cust_id上的cust_info c内部联接bill_info b的余额=b.party_id内部联接p.cust_id上的paid_info p=b.cust_id按p.cust_id分组;我试过了谢谢,它在字段列表中给出1052列“cust_id”是模糊的谢谢,它在字段列表中给出1052列“cust_id”是模糊的
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 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
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
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