我正在尝试在sql中按一定数量对结果进行分组。即如果我有60行并且我想按10组分组,我将有6组10行,反映表中结果的当前顺序(在每组中我将得到总数或平均值该组中的行)。有没有办法做到这一点?
答案 0 :(得分:2)
MS SQL (sqlfiddle):
WITH cte(groupNumber, Id) AS
(
SELECT
(ROW_NUMBER( ) OVER ( ORDER BY Id )) / 10 AS groupNumber,
Id
FROM
MyTable
)
SELECT
MAX( Id ),
groupNumber
FROM
cte
GROUP BY
groupNumber;
MySQL (sqlfiddle):
SELECT
MAX( Id ),
groupNumber
FROM
(
SELECT
Id,
CAST( FLOOR( (@a := @a + 1 ) / 10 ) AS UNSIGNED ) AS groupNumber
FROM
MyTable
ORDER BY
Id
) AS tmp,
(SELECT @a := 0) r
GROUP BY
groupNumber;
答案 1 :(得分:0)
我会这样做:
答案 2 :(得分:-1)
选择 a look to this。当首先使用mysql问题进行堆叠时,您可以使用此站点。