I’m getting an unexpected result for my query in group function. I’m using the following 3 tables:
salewith columnsAccountId,NetAmount,quantity,datePurchasecolumnsAccountId,NetAmount,quantity,dateAccountcolumnsAccountId,AccountName
I made a stored procedure that takes two inputs: Date1 and Date2.
I need to calculate the following:
Account.AccountName- sum of
NetAmountofPurchase - sum of
NetAmountofSalewithDatebeforeDate - sum of
NetAmountofPurchase– sum ofNetAmountofSaleforDatebetweenDate1andDate2 - sum of
NetAmountofSaleandPurchaseforDatebetweenDate1andDate2
I’m currently doing this:
SELECT a.SecurityName,
Sum( d.NetAmount) - Sum(e.NetAmount)As 'Opening Amount',
Sum( d.Quantity) - Sum(e.Quantity) As 'Opening Number',
Sum( d.NetAmount) / Sum( d.Quantity)As 'Opening Rate',
Sum( s.Quantity) As 'Number',
Sum( s.NetAmount) / Sum( s.Quantity) As 'Rate',
Sum( s.NetAmount) As 'Amount',
Sum( p.Quantity) As 'Number',
Sum( p.NetAmount) / Sum( p.Quantity) As 'Rate',
Sum( p.NetAmount) AS 'Amount',
IsNull(Sum( d.Quantity), 0) + (Sum( p.Quantity)) - IsNull((Sum( s.Quantity)), 0) As 'Closing Number',
IsNull(Sum( d.NetAmount),0)+(Sum( p.NetAmount)) -IsNull((Sum( s.NetAmount)),0) As 'Closing Amount',
IsNull(Sum( d.Rate),0)+(Sum( p.Rate))-IsNull((Sum( s.Rate)),0) As 'Closing Rate'
FROM Sale s
left Join SecurityAccount a ON s.SecurityAccountId = a.SecurityAccountId
Right JOIN Purchase p ON a.SecurityAccountId = p.SecurityAccountId
Left JOin Purchase d On a.SecurityAccountId=d.SecurityAccountId
And d.Date < @PeriodStart
Left Join Sale e On a.SecurityAccountId=e.SecurityAccountId
And e.Date < @PeriodStart
Group by a.SecurityName
End
But I’m getting values 3 times greater than expected.
Can anyone tell me what should i do?
You are joining tables 4 times by the same field
SecurityAccountId. Each join will result multiplying of result rows. The only way I see is to create 4 subqueries with grouping and then using those results in main query. This should work, if I have no mistakes 🙂