简体   繁体   中英

SQL Group By groups of n?

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.

select
    (mod(id, 2) + id)/2 as id_group,
    max(data) as max_data
from tableA
group by 1

See this query running in sqlfiddle

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

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, 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

And the updated SQLfiddle...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM