I need to group some rows in a database, in groups of n.
Example:
select max(data) from tableA group by (groups of 2) order by id;
result: 20, 30, 5
so…
group 1 holds id 1 & 2, group 2 holds id 3 & 4, and group 3 would hold id 5 & 6.
tableA
| id | data |
---------------
| 1 | 10 |
| 2 | 20 |
| 3 | 15 |
| 4 | 30 |
| 5 | 5 |
| 6 | 0 |
---------------
Is there a way to achieve this using SQL?
Note: The system is running on MySql.
Since the
GROUP BYcan hold an arbitrary expression, you can useCASEto return theidif its valueMOD 2is equal to 1, andid - 1otherwise. This groups them in pairs incrementing from 1.Here is a demo on SQLfiddle.com
Allow for non-sequential ids
Update
Overnight I felt badly about the fact that this solution only works correctly for sequential values of
id. If you deleted rows, you would no longer get correct results. So here is a version that accounts for non-sequential, gappedids:And the updated SQLfiddle…