Do you have an idea about how to resolve this?
This is an example of the DB I have: profile_table
user_id status points created_at
01 1 20 2011-01-01 01:03:35
02 1 50 2011-01-02 01:03:35
03 1 800 2011-01-04 01:03:35
04 1 152 2011-02-15 01:03:35
05 1 388 2011-02-20 01:03:35
06 0 40 2011-02-25 01:03:35
07 1 246 2011-02-26 01:03:35
08 1 335 2011-02-27 01:03:35
09 1 521 2011-03-08 01:03:35
10 1 5354 2011-03-14 01:03:35
11 0 22 2011-03-18 01:03:35
12 1 234 2011-04-03 01:03:35
13 1 222 2011-04-05 01:03:35
14 1 396 2011-04-24 01:03:35
Second Table: spend_points
price_id spend_points created_at
1 20 2011-01-01 01:03:35
2 10 2011-01-02 01:03:35
3 30 2011-01-05 01:03:35
8 40 2011-01-06 01:03:35
14 10 2011-02-03 01:03:35
7 50 2011-02-06 01:03:35
14 10 2011-02-07 01:03:35
2 10 2011-03-03 01:03:35
14 60 2011-03-12 01:03:35
14 10 2011-04-07 01:03:35
2 70 2011-04-12 01:03:35
14 80 2011-04-15 01:03:35
14 20 2011-04-21 01:03:35
The first table belongs to a group and this group can only spend points on items with ‘price_id’ = 14. In the spend_points table we have all items spend and there are some 14’s.
The query I’m trying to build should show data from all users who can spend on price_id = 14. The table should have the total of points they have, total of spend points and all points they have had so far. Sounds easy when you only want that data but the problem to me is when I try to make a history of this. Every new month it should show an update of the previos month and also the previous month and so on.
Status = 0 means Inactive and
So the final table should look like this.
Detail January February March April
Total Active Users 3 7 9 12
Total Inactive Users 0 1 2 2
Total Point 807 2031 7928 8780
Spend Points 0 20 80 190
Points So Far 807 2051 8008 8970
Do you guys have any idea how to do it? :'(
It’s long, but it will do it… based on a single year basis… if your data spans years, just add an applicable “year” where clause to each select/union. The premise of the query is to pre-declare up front each month so we know where the “cut-off” date is for a given month aggregation (ie: Jan is sum of all less than Feb, Feb is sum all up to Mar, etc).
Each one does require it’s own pivot roll-up per month which is what makes this long, however, very simple to follow to get your results. Not how I would plan to have such a query, especially on a large set — where I would prefer to have a single table with “roll-up” values per month/year of the expected aggregations, and where applicable, have a trigger just update the counts, points, whatever as needed.