!Modified!
I have a table (mySQL 5.0.x) which contains values for date ranges.
| id | link_id | type_id | value | start | end |
====================================================
| 1 | 1 | 1 | 10 | 201111 | 201202 |
| 2 | 1 | 2 | 20 | 201110 | 201201 |
| 3 | 1 | 1 | 100 | 201202 | 201202 |
| 4 | 2 | 1 | 40 | 201202 | 201203 |
where
- id is the id for record
- link_id is for linking the data to other tables
- type_id is for determining the type of the value from other table
- value is numerical value
- start and end define the range (real date or integer for year and month)
The trick is that I need to present total value per type and link for a given period on a monthly basis. So the result should be like this for the range 201201 – 201202:
| period | link_id | type_id | value |
======================================
| 201201 | 1 | 1 | 10 |
| 201202 | 1 | 1 | 110 |
| 201201 | 1 | 2 | 20 |
| 201201 | 2 | NULL | NULL |
| 201202 | 2 | 1 | 40 |
I could use PHP to put the information like this into the database but there are some drawbacks. I have hundreds of link_ids, many type_id, and the average difference between start and end dates is 30 months so I would have tons of rows.
Here’s one way to do it. I’ve put in
$startMonthand$endMonthso you can see how they play in. (I have this niggling feeling this can be simplified, but it currenty escapes me):The way it works: suppose you had a table
a:Then the query you’re after is a lot simpler to work out:
Ie you join table
atofooby making sure themonthis between the start and end periods, and then you just sum up value, grouping by month, link id, and type id.So the problem is how to generate table
awhich contains numbers from$startMonthto$endMonth. Hence the:This gives a table of numbers startign from
201201and with 2 rows, ie up to201202. In this query theFROM foois dummy – not really used.