For each group of TS
, there's random number of rows that having different Name
and it's Count
. I would like to do the following:
- Get latest group of TIMESTAMP with NAME order desc by
Count
. For more than 3 rows in the latest group, the rest sum byCount
and rename as "Other". - For each of the
TIMESTAMP
group, find rows havingNAME
in step 1. - If not found, 0 padding as
Count
for the pair in specific group.
Have a look at the illustration:
TS | Name | Count
=============================
1552286160 | Apple | 7
1552286160 | Orange | 8
1552286160 | Grape | 8
1552286160 | Pear | 9
1552286160 | Kiwi | 10
1552286160 | Berry | 3
1552286160 | Carrot | 2
1552286100 | Apple | 10
1552286100 | Orange | 12
1552286100 | Grape | 14
1552286100 | Pear | 16
1552286100 | Kiwi | 9
1552286040 | Apple | 4
1552285980 | Peach | 8
With this dataset, I would like to have the following:
TS | Name | Count
=============================
1552286160 | Kiwi | 10
1552286160 | Pear | 9
1552286160 | Grape | 8
1552286160 | Other | 8 + 7 + 3 + 2
1552286100 | Kiwi | 9
1552286100 | Pear | 16
1552286100 | Grape | 14
1552286100 | Other | 10 + 9
1552286040 | Kiwi | 0
1552286040 | Pear | 0
1552286040 | Grape | 0
1552286040 | Other | 4
1552286040 | Kiwi | 0
1552286040 | Pear | 0
1552286040 | Grape | 0
1552286040 | Other | 8
This is actually an extended solution came from MySQL top-N ranking and sum the rest of same group However, the solution does not group each TS
group with the same rows from the latest TS
group, in this case TS=1552286160
.
The SQL Fiddle that I've prepared is located here: http://sqlfiddle.com/#!9/4e13004/1
Thanks if you have any idea.