這應該讓你走上正確的道路。您可以與您的實際數據庫隔離運行以下代碼。
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
請張貼一些示例數據 – mohan111
聽起來像你只需要一些分組,但沒有適當的架構不能幫助和示例數據 – Tanner
請參閱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