I have this very tricky problem and Im trying to figure it out for a while now,
I have this query result set
SELECT * FROM Orders
OrderID | OrderAmount | OrderDate | Expiry Date
1 $100 2008-01-01 2009-12-31
2 $200 2009-01-01 2010-12-31
3 $300 2010-01-01 2011-12-31
4 $3 2010-01-01 2010-06-31
5 $400 2007-01-01 2009-05-31
Now, how can i break down each order by OrderDate – ExpiryDate daterange per YEAR
I want the result something like this in my RDLC report
ORDERS CONSUMED PER YEAR
OrderID | YEAR | Consumed Amount
1 2008 $50
1 2009 $50
2 2009 $100
2 2010 $100
3 2010 $150
3 2011 $150
4 2010 $3
5 2007 $160
5 2008 $160
5 2009 $80 <---- another tricky part
The computation is base on the term, eq. (2 year term of $300 means $150 per year)
How can i do this in MS-SQL Query?
** I know the title seems incorrect ^^, i just cant find the right title
Edited: added more samples and explanation
If this is SQL Server 2005 or later, you can use a common table expression to recursively build a table of months and use that to calculate the order amount consumed per year.
A few notes:
This solution assumes that the time periods are based on whole months. The approach is to determine the amount of the order consumed per month, then multiply that by the number of months in the year. You could modify this to use an amount consumed per day if needed.
In the final
select, I cast frommoneyto adecimalwith higher precision to try and avoid rounding problems. You may have to adjust this to fit your needs, but I’m not sure that you will be able to avoid rounding problems entirely.The results for OrderID 5 don’t match your sample results. This is because the example has 5 months in 2009, not 6.
And the results: