Jes Sie

Jes Sie

  • 699
  • 1.2k
  • 265.2k

Aggregates in SQL Server involving 3 tables

Sep 8 2017 4:21 AM
Hello DBA's, I need some help. I have 3 tables namely: Credit Limit, Sold, Paid. What I need are the following:
1. I need to subtract the Paid from the Sold (we'll call this Unpaid)
2. I need to get the remaining Credit Limit by subtracting Credit Limit against Unpaid.
 
below is my query but it gives me a wrong result:
  1. declare @CreditLimit table  
  2. (  
  3.     [AgentName] [nvarchar](50),  
  4.     [AgentID] [nvarchar](50),  
  5.     [CreditLimit] [decimal](18, 2)  
  6. )  
  7. INSERT into @CreditLimit  
  8. SELECT   
  9.     a.AgentName,  
  10.     a.AgentID,  
  11.     a.CreditLimit  
  12. FROM [dbo].[Agents] a  
  13.   
  14.   
  15. DECLARE @SoldInsurance table  
  16. (  
  17.     [AgentID] nvarchar(50),  
  18.     [TotalPremium] [decimal](18, 2)  
  19. )  
  20. insert into @SoldInsurance  
  21. SELECT m.AgentID, SUM(m.TotalPremium)   
  22. FROM tblMotorInsurance_eCI M  
  23. group by m.AgentID  
  24.   
  25. declare @PaidInsurance table  
  26. (  
  27.     [AgentID] nvarchar(50),  
  28.     [ConvertedNetPremium] [decimal](18, 2),  
  29.     [ConvertedRegistryFee] [decimal](18, 2),  
  30.     [ConvertedVAT] [decimal](18, 2)   
  31. )  
  32. INSERT INTO @PaidInsurance  
  33. SELECT t.AgentID, sum(isnull(t.ConvertedNetPremium,0)), sum(isnull(t.[ConvertedRegistryFee],0)), sum(ISNULL(t.[ConvertedVAT],0)) AS PAYMENT  
  34. FROM TaxInvoiceDetails t  
  35. group by t.AgentID  
  36.   
  37. SELECT  c.AgentName,  
  38.          C.AgentID,  
  39.         isnull(C.CreditLimit,0) as CreditLimit,  
  40.         isnull(m.TotalPremium,0) as InsuranceSold,  
  41.         isnull(T.ConvertedNetPremium,0) + isnull(t.ConvertedRegistryFee,0) + isnull(t.ConvertedVAT,0) as PaidInsurance,  
  42.         isnull(M.TotalPremium,0) - isnull(T.ConvertedNetPremium,0) - isnull(t.ConvertedRegistryFee,0) - isnull(t.ConvertedVAT,0) as UnpaidInsurance,  
  43.         ISNULL(c.CreditLimit,0) - isnull(M.TotalPremium,0) - isnull(T.ConvertedNetPremium,0) - isnull(t.ConvertedRegistryFee,0) - isnull(t.ConvertedVAT,0) as RemainingCreditLimit  
  44. FROM @CreditLimit c left outer join @SoldInsurance m on c.AgentID = m.AgentID  
  45.             left outer join @PaidInsurance t on m.AgentID = t.AgentID  
  46. where m.AgentID = '00003'  
  47. --where 1=1  
I ran it and it gaves me this:
  1. credit limit         sold             paid          unpaid     remaining credit limit  
  2.  50,000,000.00   58,232,073.40   32,487,325.40   25,744,748.00   (40,719,398.80)  
 the paid and unpaid part is correct but on the Remaining Credit Limit is wrong. Please advice. Thank you.
 
 

Answers (2)