Edit - I found it different from pivot table. Because in my case, it based on date
I have table with linked data. I want to return the most recent activity per customer into column, like temporal data for data mining purpose.
So I have these columns in my table:
id_user | item_id | date
1 | 2 | 2016-11-10
1 | 3 | 2016-9-9
1 | 23 | 2016-8-8
1 | 21 | 2016-6-6
1 | 5 | 2016-7-7
1 | 4 | 2016-10-10
2 | 3 | 2016-9-9
2 | 4 | 2016-10-10
2 | 21 | 2016-5-4
3 | 4 | 2016-10-10
3 | 4 | 2016-9-9
First - I want to filter data to get "recent 5" activity. Then I comes up with this code
set @num := 0, @group := '';
select x.`id_user`, x.`item_id`, x.`date`
from
(
select `id_user`, `item_id`, `date`,
@num := if(@group = `id_user`, @num + 1, 1) as row_number,
@group := `id_user` as dummy
from ratings
order by `id_user`, `date` desc, `item_id`
) as x,
where x.row_number <= 5
ORDER BY x.`user_id`, x.date DESC;
Those code give me this table:
id_user | item_id | date
1 | 2 | 2016-11-10
1 | 4 | 2016-10-10
1 | 3 | 2016-9-9
1 | 23 | 2016-8-8
1 | 5 | 2016-7-7
2 | 4 | 2016-10-10
2 | 3 | 2016-9-9
2 | 21 | 2016-5-4
3 | 4 | 2016-10-10
3 | 4 | 2016-9-9
BUT - I want something like this for data-mining puspose
Id_user | item_1 | Item_2 | Item_3 | Item_4 | Item_5
1 | 2 | 4 | 3 | 23 | 5 |
2 | 4 | 3 | 21 | NULL | NULL |
3 | 4 | 4 | NULL | NULL | NULL |
Did you get my idea? Sorry, if I can't explain it clearly, hope you can understand what I want.
The Question
- How can I make the SQL query for these issue? (currently I got RAW Data from MySQL database)
- Is there any better approach for this issue? I hope it's a best practice.