我有桌子
+-----+----------+---------+
| id | name | phase |
+-----+----------+---------+
| 101 | Bolt | PHASE 1 |
| 102 | Nut | PHASE 1 |
| 103 | Screw | PHASE 1 |
| 104 | Hex BOLT | PHASE 1 |
| 105 | Rubber | PHASE 1 |
| 106 | Aluminum | PHASE 2 |
| 107 | Slate | PHASE 2 |
| 108 | Pen | PHASE 3 |
| 109 | Pencil | PHASE 3 |
| 110 | Mouse | PHASE 3 |
| 111 | Keyboard | PHASE 3 |
+-----+----------+---------+
我想创建另一列,我必须在其中放置行号。
逻辑:对于3行,应该相同,然后更改为第4行的下一个值。而且无论何时PHASE发生变化,即使前一个数字的3组不完整,它也应转到下一个数字。
预期输出
+-----+----------+---------+-----+
| id | name | phase | SET |
+-----+----------+---------+-----+
| 101 | Bolt | PHASE 1 | 1 |
| 102 | Nut | PHASE 1 | 1 |
| 103 | Screw | PHASE 1 | 1 |
| 104 | Hex BOLT | PHASE 1 | 2 |
| 105 | Rubber | PHASE 1 | 2 |
| 106 | Aluminum | PHASE 2 | 3 |
| 107 | Slate | PHASE 2 | 3 |
| 108 | Pen | PHASE 3 | 4 |
| 109 | Pencil | PHASE 3 | 4 |
| 110 | Mouse | PHASE 3 | 4 |
| 111 | Keyboard | PHASE 3 | 5 |
+-----+----------+---------+-----+
我已经尝试过以下查询,但未提供所需的输出。
select *, (row_number() over (order by phase)-1) / 3 as sets
from table_main
实际输出:
+-----+----------+---------+------+
| id | name | phase | sets |
+-----+----------+---------+------+
| 101 | Bolt | PHASE 1 | 0 |
| 102 | Nut | PHASE 1 | 0 |
| 103 | Screw | PHASE 1 | 0 |
| 104 | Hex BOLT | PHASE 1 | 1 |
| 105 | Rubber | PHASE 1 | 1 |
| 106 | Aluminum | PHASE 2 | 1 |
| 107 | Slate | PHASE 2 | 2 |
| 108 | Pen | PHASE 3 | 2 |
| 109 | Pencil | PHASE 3 | 2 |
| 110 | Mouse | PHASE 3 | 3 |
| 111 | Keyboard | PHASE 3 | 3 |
+-----+----------+---------+------+
我也尝试过DENSE_RANK()
,但没有获得预期的输出。
尝试一下:
WITH CTE
as
(
select *, ROW_NUMBER () OVER (PARTITION BY phase ORDER BY id) as rn
from table_main
)
SELECT *,DENSE_RANK() over (ORDER BY phase ,CEILING(rn/3.0)) as set
FROM CTE
使用LAG
获取LAG
的上一行值,如果更改,则添加column
。如1
所述,使用ROW_NUMBER()
,然后像下面一样%3
这些值。
sum