2013-07-08 159 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