2012-10-30 53 views
-4

有三個表,我們必須使用一個主鍵和外鍵從這些表中選擇數據。但是在一個表中,第三個表中有很多數據。我們必須在主鍵的基礎上總結數據。SQL中的SUM函數

Table1Table2table3

BAl = Balance, met = Method, amo = amount, cst_id, cut_id, cut_i = customer_id 

現在,我們要總結的方法和總和在同一查詢10卡斯特ID的基礎上。誰可以幫我這個事?

+0

@MahmoudGamal這就是我之所以有顯示錶 – Ashishsingh

+0

我必須的scema選擇10客戶同時 – Ashishsingh

回答

0

如果您提供一些示例數據,編寫查詢將更容易幫助您。 但是,如果你的MET字段是數字,你想總結它,那麼你需要。

select 
    t1.cst_n, t2.bal, 
    sum(t3.met) as met, 
    sum(t3.amo) as amo 
from table1 as t1 
    inner join table2 as t2 on t2.cut_id = t1.cst_id 
    inner join table3 as t3 on t3.cut_i = t1.cst_id 
group by t1.cst_n, t2.bal 

好,如果你想要爲所有10個客戶數據總結成一個數字,可能你只需要

select 
    sum(t3.met) as met, 
    sum(t3.amo) as amo 
from table3 as t3 
where t3.cut_i in (select t.customerid from @<your variable table with cust. ids> as t) 
+0

它只會給一個客戶....我需要一個查詢 – Ashishsingh

+1

爲10個客戶相同請給測試數據。此查詢按'cst_n'(假設客戶編號)分組客戶 –

0
;WITH cte 
AS 
(
    SELECT 
     *, 
     ROW_NUMBER() OVER (ORDER BY t1.cst_id) RowNum 
    FROM Table1 t1 
    INNER JOIN Table2 t2 
      ON t1.cst_id = t2.cut_id 
    INNER JOIN Table3 t3 
      ON t2.cut_id = t3.customer_id 
      AND t2.BAL = t3.Balance 
      AND t2.amo = t3.amount 
) 
SELECT SUM(*) 
FROM cte 
WHERE RowNum Between 1 AND 10 
-- You can add a GROUP BY here 
+0

cte是什麼? – Ashishsingh

+0

@Ashishsingh - 它是[Common table expression](http://msdn.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx),我使用它,只是爲了便於閱讀,並且分頁讓您每次選擇10位客戶的總和。您可以使用子查詢編寫它。 –