2016-10-24 79 views
0

雙我有3個表減去資金金額在SQL

client,fees,financial 

我想

  • 和所有的費用(fees.fee)客戶端「925 '並減去任何付款(financial.payment)。
  • 顯示客戶端姓氏(client.lastname)。

費用和財務表格是FK到client.Id通過fees.clientId和financial.clientId。

我認爲這很簡單,但個別陳述顯示正確的金額,但加入後,由於收取了許多費用和一次付款,所以它們成倍增加。

我已經嘗試了很多不同的聲明,並且剛剛接觸sql是完全難住的。

有人可以指示我在點上的示例或幫助編寫此選擇語句。

任何幫助,將不勝感激。

+2

請張貼一些示例數據 – mohan111

+0

聽起來像你只需要一些分組,但沒有適當的架構不能幫助和示例數據 – Tanner

+0

請參閱http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple- sql-query – Strawberry

回答

0

這應該讓你走上正確的道路。您可以與您的實際數據庫隔離運行以下代碼。

CREATE TABLE #client 
    ( 
     id INT, 
     name NVARCHAR(10) 
    ) 

CREATE TABLE #fees 
    (
     clientId INT , 
     fees DECIMAL(18, 2) 
    ) 

CREATE TABLE #financials 
    (
     clientId INT , 
     payment DECIMAL(18, 2) 
    ) 

INSERT INTO #client (id, name) 
VALUES (925, N'Company A') 

INSERT INTO #fees (clientId , fees) 
     SELECT 925 , 120.00 
     UNION ALL 
     SELECT 925 , 20.00 
     UNION ALL 
     SELECT 925 , 200.00 
     UNION ALL 
     SELECT 925 , 60.00 

INSERT INTO #financials (clientId , payment) 
     SELECT 925 , 125 
     UNION ALL 
     SELECT 925 , 250 
     UNION ALL 
     SELECT 925 , 75 

-- total fees = 400 
SELECT clientId , 
     SUM(fees) Fees 
FROM #fees 
GROUP BY clientId 

-- total paid = 450 
SELECT clientId , 
     SUM(payment) Paid 
FROM #financials 
GROUP BY clientId 

-- Single query with difference 
SELECT c.id , 
     c.name , 
     TotalFees , 
     TotalPaid , 
     f.TotalFees - fi.TotalPaid AS FeesLessPaid 
FROM #client c 
     INNER JOIN (SELECT clientId , 
          SUM(fees) TotalFees 
        FROM #fees 
        GROUP BY clientId 
        ) f ON f.clientId = c.id 
     INNER JOIN (SELECT clientId , 
          SUM(payment) TotalPaid 
        FROM #financials 
        GROUP BY clientId 
        ) fi ON fi.clientId = c.id 

DROP TABLE #client 
DROP TABLE #fees 
DROP TABLE #financials 

產地:

id name  TotalFees TotalPaid FeesLessPaid 
925 Company A 400.00  450.00  -50.00 
+0

我比較喜歡與其他表左外部客戶端。它不會錯過任何客戶。 –

0

嘗試類似如下:

SELECT CO.LASTNAME,COALESCE(A.FEE,0)-COALESCE(B.PAYMENT,0) AMT_LEFT 
FROM CLIENT CO 
LEFT OUTER JOIN 
    (
    SELECT C.CLIENTID,SUM(F.FEE)FEE 
    FROM CLIENT C 
    INNER JOIN FEES F 
    ON C.CLIENTID=F.CLIENTID)A 
ON CO.CLIENTID=A.CLIENTID 
LEFT OUTER JOIN 
    (
    SELECT C.CLIENTID,SUM(F.PAYMENT)PAYMENT 
    FROM CLIENT C 
    INNER JOIN FINANCIAL F 
    ON C.CLIENTID=F.CLIENTID)B 
ON CO.CLIENTID=B.CLIENTID