合并表后,我得到了以下结果
| id | count | some_id |
| 0 | 0 | 1 |
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 7 | 1 |
| 4 | 12 | 1 |
| 5 | 1 | 2 |
| 6 | 2 | 2 |
| 7 | 5 | 2 |
and so on...
每some_id
,我需要将count
更改为正确的计数序列
我需要的结果是
| id | count | some_id |
| 0 | 0 | 1 |
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 3 | 1 |
| 4 | 4 | 1 |
| 5 | 0 | 2 |
| 6 | 1 | 2 |
| 7 | 2 | 2 |
and so on...
假设some_id
为0<some_id<n
有没有办法可以做到这一点?我唯一想到的就是使用循环,除此之外还有其他方法吗?
答案 0 :(得分:1)
用户 ROW_NUMBER()
SELECT
id,
-1 + ROW_NUMBER() OVER (PARTITION BY some_id ORDER BY some_id) as [Count],
some_id
FROM YourTable
答案 1 :(得分:0)
您必须使用DENSE_RANK来实现相同的目标: -
SELECT id, DENSE_RANK() OVER (ORDER BY some_id) AS 'Count', some_id
FROM your_table;