我有一张table
+-----+----------+---------+
| 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行的下一个值。当相位改变时,它应该转到下一个数字,即使前一个数字的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()
但没有得到预期的产出。
在这里摆弄
2条答案
按热度按时间rbpvctlc1#
试一试:
c3frrgcw2#
使用
LAG
获取的上一行值column
如果它改变了,那么加上1
. 使用ROW_NUMBER()
如前所述%3
然后sum
这些值如下所示。