2013-07-08 76 views
0

我有以下表结构,SQL内部联接查询

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 

现在我的输出应在2个bill_dates日期为单列之间显示的记录(2013年1月1日至2013年2月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

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

回答

1

您希望加入3个表格,然后按照bill 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 

按组的快速概览:这需要你的结果集,并smoosh行在一起,根据他们对你给它的列相同的数据。由于每张账单将具有相同的客户姓名,金额,日期等,因此我们可以根据账单ID以及账单ID进行分组,并且我们会为每个账单记录。但是,如果我们想通过p.paid_amount对它进行分组,因为每次付款都会有不同的付款(可能),所以您会为每笔付款记录一笔记录,而不是每笔付款记录, d想要。一旦group by将这些行擦除在一起,就可以运行聚合函数(如SUM(column))。在这个例子中,SUM(p.paid_amount)合计了具有该bill_id的所有付款,以计算出已付多少款。有关更多信息,请参阅他们的SQL教程中的W3Schools chapter on group by

希望我已经正确理解了这一点,这可以帮助你。

+0

由于克雷格,它的工作!但我不太了解如何传播这个查询,因为我是新来的sql ... :) –

+0

@Nikhil,好吧,我已经扩大了我的答案,一些评论和解释,希望能让事情变得更清楚。希望这可以帮助。 –

+0

是的。这是很好的解释。谢谢。 –

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