I'm trying to make some data, and don't do SQL gymnastics often enough to find out what function I'm looking for. I would call it "ungroup by". I have a SELECT that displays this, reflecting a series of monthly subscription positions: when they were created, closed, and how many monthly expenses:
+----+---------------------------------+------------+------------+------------+ | id | description | created_on | closed_on | monthly | +----+---------------------------------+------------+------------+------------+ | 3 | Daily horoscope email | 2012-01-01 | null | 10000.0000 | | 5 | Pet food delivery | 2012-01-05 | null | 3500.0000 | | 6 | Dirty magazine subscription | 2012-01-09 | null | 1500.0000 | | 7 | Stupid nuts posted in a box | 2012-01-01 | 2012-01-04 | 1500.0000 | .... etc ...
What I'm trying to do is run the "execution speed" daily. Thus, each day is transferred with the current total current monthly obligation, that is, the above data will be displayed on:
+------------+----------+ | date | run_rate | +------------+----------+ | 2012-01-01 | 11500 | | 2012-01-02 | 11500 | | 2012-01-03 | 11500 | | 2012-01-04 | 10000 | | 2012-01-05 | 13500 | | 2012-01-06 | 13500 | | 2012-01-07 | 13500 | | 2012-01-08 | 13500 | | 2012-01-09 | 15000 |
What I think is possible is to create a temporary table with one row for each day, and then write a LEFT JOIN / GROUP BY statement that references the first table to create my output. But I can only see how to create an everyday βdifferenceβ, and not the total amount, and I need to βungroupβ the first table into two records, a positive record to create a subscription, and a negative record when it is closed.
I would like to stick with MySQL and, if possible, in one mega statement. If this is not possible, I can add some stored procedures or temporary tables to my query structure. Or do I really need to grind my data through Ruby? (I know exactly how, but I hoped that I could keep all my logic in one place, and I'm trying to improve our current slow calculation, which uses ActiveRecord).
source share