Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
Mickel
Starting Member
2 Posts |
Posted - 2011-08-18 : 13:46:07
|
| I have been challenged with the following problem. I am looking for a way to get the historical record state per period using the start date and end date of that record.Example:Product A is valid from 15-jan-2011 till 14-jul-2011Product B is valid from 31-mar-2011 till 4-nov-2011Product C is valid from 4-jun-2011 till 5-dec-2011The table would have the fields Product, start date, end dateI would like to create a query that would list the total number of valid records per period (month, quarter, year) in which the user is able to enter the reporting period. Thus:User input: 1-mar-2011 till 31-aug-2011, monthly would produce:Mar 2011: 2 --> product A and BApr 2011: 2 --> product A and BMay 2011: 2 --> product A and BJun 2011: 3 --> product A, B and CJul 2011: 3 --> product A, B and CAug 2011: 2 --> product B and CNew user input: 1-jan-2011 till 31-dec-2011, quarterly would produce:Q1 2011: 2 --> product A and BQ2 2011: 3 --> product A, B and CQ3 2011: 3 --> product A, B and CQ4 2011: 2 --> product B and CI only need the period and a count of the number of valid records of that period, correctly sorted by period (for example by month). I do not the list of products. If helpful I have a table of dates that could be joined (date, month number, month name, quarter, year)Which SQL wizard is able to help me achieving this goal? |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2011-08-18 : 14:03:15
|
you need a calendar table like belowhttp://visakhm.blogspot.com/2010/02/generating-calendar-table.htmland use it like below for monthlySELECT MONTH(MonthDate),YEAR(MonthYear),PCntFROM(SELECT DISTINCT DATEADD(mm,DATEDIFF(mm,0,Date)+1,0)-1 AS MonthDateFROM dbo.CalendarTable(@startdate,@enddate,0) )fCROSS APPLY (SELECT COUNT(Product) AS Pcnt FROM Table WHERE f.MonthDate BETWEEN StartDate AND EndDate)p for quarterly replace mm with qq for date manipulation functions------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
Mickel
Starting Member
2 Posts |
Posted - 2011-08-19 : 21:14:11
|
| Thank you for your help. It needed a little tweaking, but with your help I got the job done. Well done! :)___________________________http://www.e-controller.eu |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2011-08-20 : 01:19:59
|
| welcome------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|
|
|