I am using MySQL to create a window function per category in another column. I am thinking of maybe combining a pivot table with a window function, however, do not know how to do a pivot table with MySQL.
Below is what I have in mind to do, create a column per cateogry and calculate the average over a given time range:
I have:
firstname | lastname | category | amount | timestamp |
---|---|---|---|---|
Tom | Sta | hair | 1 | 2020-06-21 |
Chris | Danny | school | 2 | 2020-06-22 |
Gee | Elle | books | 1 | 2020-06-21 |
Tom | Sta | books | 10 | 2020-06-23 |
Chris | Danny | hair | 2 | 2020-06-25 |
Gee | Elle | school | 15 | 2020-06-28 |
I want:
firstname | lastname | hair_last_3_days | school_last_3_days | boks_last_3_days |
---|---|---|---|---|
Tom | Sta | 1 | 1 | 21 |
Chris | Danny | 2 | 2 | 202 |
Gee | Elle | 2 | 1 | 1 |
Tom | Sta | 4 | 10 | 6 |
Chris | Danny | 3 | 2 | 0 |
Gee | Elle | 2 | 15 | 28 |
At the moment I'm able to create the averages
select first, last, date(trans_date_trans_time), amt, category,
avg(amt) over(partition by first, last, category order by date(trans_date_trans_time) ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) avg_last_3 from table;
However I realise that this will only work if the days are one after the other and won't work if there are two rows from the same day for one person. I'm looking for some help. Thanks