A distributor have various outlets to sale products. Products are based on categories.
Outlets can receive products from the distributors and from other outlets (transfers). Opening balance (Qty), receipt (Qty), transfer IN (Qty), transfer Out (Qty), sale (Qty), closing balance (Qty) of every day is maintained in a table txnTransactions
. The structure of the table is follows:
Create table txnTransactions
(
dDate datetime,
iCategoryID int (FK),
iProduct ID int (FK),
iOutletID int (FK),
iOpeningBalance int,
iReceipt int,
iTranIN int,
iTranOut int,
iSale int,
iClosingBalance int
)
A report is to be shown to the distributor for the total transactions (product-wise) within a specified period (Ex. 01/03/2013 to 31/03/2013) for all the outlets (I have used 0 as value to check if it is all outlets or specific outlet).
In this report the Opening Balance of all the Products is to be retrieved only of the start day (Ex. 01/03/2013) and then the total (sum) of all the other fields (Product-wise) is to be shown.
I have achieved the same with the help of temp tables. But the query takes a very long time that results in the Time out. If I use simple group by I need to use aggregate function for Opening Balance that results in wrong data.
Select
sum(iOpeningBalance), sum(iReceipt), sum(TranIN), sum(TranOut), sum(Sale)
from
txnTransactions
where
datediff(d, dDate, @startDate) <= 0
and datediff(d, dDate, @endDate) >= 0
group by
iProductID
Don't want to use sum(iOpeningBalance)
...
The sample output is as follows:
ProductID OpeningBalance Receipts TranIN TranOut Sale Total/Balance
1 10 100 40 50 50 50
2 35 165 50 100 50 100
3 3 147 10 60 10 90
The opening balance is of the startdate and all other fields are the sum of the duration provided by startdate & enddate (input params for procedures).
Total/Balance is: openingbalance + sum(receipts) + sum(TranIn) - sum(TranOut) - sum(Sale)
Need help to optimize the query. Thanks in advance.