2

如何实现这个(SQL)?

我的桌子

id    sub
1      1
2      1
3      1
4      1
5      1
6      2
7      2
8      2

结果应该如下所示

groupid   id   sub              groupid    id    sub
   0       1    1                   0       1    1
   0       2    1                   0       2    1
   0       3    1                   0       3    1
   1       4    1         or        1       6    2
   1       5    1                   1       7    2
   2       6    2                   1       8    2
   2       7    2
   2       8    2

我目前的查询是

SELECT (id - 1) / 3 groupid, id, point FROM student
4

2 回答 2

4

编辑:DENSE_RANK()我最初的答案中的第一个可以被消除,以简单地结束;

WITH cte AS (
  SELECT ROW_NUMBER() OVER (PARTITION BY SUB ORDER BY ID) as rn, id, sub
FROM student)
SELECT DENSE_RANK() OVER (ORDER BY sub,(rn-1)/3) as groupid, id, sub FROM cte;

一个用于测试的 SQLfiddle

——原始答案——

假设 SQL server,你可以利用DENSE_RANK()你的优势;

WITH cte AS (
  SELECT DENSE_RANK() OVER (ORDER BY sub) AS rank,
         ROW_NUMBER() OVER (PARTITION BY SUB ORDER BY ID) as rn,
       id, sub
FROM student)
SELECT DENSE_RANK() OVER (ORDER BY sub,rank,(rn-1)/3) as groupid,
id,sub FROM cte;

一个用于测试的 SQLfiddle

于 2013-07-10T13:24:06.270 回答
1
SELECT (id - 1) div 3 as groupid, id, point FROM student
于 2013-07-10T12:55:52.417 回答