Reputation: 145
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.
Upvotes: 1
Views: 2108
Reputation: 270677
Since the GROUP BY
can hold an arbitrary expression, you can use CASE
to return the id
if its value MOD 2
is equal to 1, and id - 1
otherwise. This groups them in pairs incrementing from 1.
SELECT MAX(data) AS maxdata
FROM tableA
/* GROUP BY the id or (id - 1) depending on the result of its modulo 2 */
GROUP BY CASE WHEN id MOD 2 = 1 THEN id ELSE (id - 1) END
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, gapped id
s:
SET @rowid = 0;
SELECT
MAX(data) AS maxdata
FROM (
SELECT
@rowid := @rowid + 1 AS rd,
data
FROM tableA
) subq
GROUP BY CASE WHEN rd MOD 2 = 1 THEN rd ELSE (rd - 1) END
Upvotes: 3