如何实现这一点(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
答案 0 :(得分: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;
- 原始答案 -
假设SQL服务器,您可以使用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;
答案 1 :(得分:1)
SELECT (id - 1) div 3 as groupid, id, point FROM student