Reputation: 121
I need advice on how to create a stored procedure, or many stored procedures for generating a monthly sales report in our company. I have shortened the tables down to make it more easy to understand:
We have two tables:
ITEM_SALES
, which consists of:
Item_ID
Name
Store
Sales_Date
Sales_Price
Quantity
And ITEM_DISCOUNT
, which consists of:
Item_ID
Name
Store
Sales_Price
Date_From
Date_To
Explanation: After each month, our different stores will send us a report on which discounts they had. These discounts can vary from one, to many days and therefor we have the Date_From, Date_to.
My idea: To make this sales report, i need a procedure that first fetches all sales in ITEM_SALES
, then checks all the discounts in ITEM_DISCOUNT
and overwrites the ones that have similar Item_ID
, Name
, and Store
for a selected period.
Example: So if a item originally had a sales_price on 99,- and then had a discount sales_price to 79,- for 2014-01-02 to 2014-01-10 it has to be overwritten for that period so the report shows the right numbers.
Is this understandable? And can anyone help me or give me some tips on the way? Is temporary tables good for this?
If more info is needed, I will provide!
Upvotes: 0
Views: 2178
Reputation: 2753
You can create the report by using LEFT JOIN
within a Stored Procedure where month and year for which report is needed, can be passed as parameter as below:
SQL Server:
CREATE PROCEDURE GetSalesReport
@month INT,
@year INT
AS
SELECT isa.Item_ID,
isa.Name,
isa.Store,
isa.Sales_Date,
COALESCE(id.Sales_Price, isa.Sales_Price) AS SalesPrice,
isa.Quantity
FROM ITEM_SALES AS isa
LEFT JOIN ITEM_DISCOUNT AS id
ON isa.Item_ID = id.Item_ID
AND isa.Name = id.Name
AND isa.Store = id.Store
AND isa.Sales_Date BETWEEN id.Date_From AND id.Date_To
WHERE MONTH(isa.Sales_Date) = @month AND YEAR(isa.Sales_Date) = @year
Upvotes: 1