使用ROW_NUMBER()对数据集进行分区

时间:2019-02-14 10:12:07

标签: sql sql-server

我对在SQL中使用ROW_NUMBER()感到有些困惑。

具有当前如下所示的数据集:

 Number ID
    1   1
    2   6
    3   11

我在下面写了一个查询:

SELECT rownum = ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Number), Number
FROM #SEQNUMBERSTEMP

哪个输出:

rownum  Number
1       1
1       2
1       3
1       4
1       5
1       6
1       1
1       2
1       3
1       4
1       1

但是我要实现以下目标:

rownum  Number
1       1
1       2
1       3
1       4
1       5
2       1    # Note 2 should start at position 6
2       2
2       3
2       4
2       5
3       1    # Note 3 should start at position 11
3       2
3       3

2 个答案:

答案 0 :(得分:4)

您可能想使用<h2> Rainbow Colours</h2> <svg height="1000" width="500"> <circle class="circle1" onclick="function()" cx="50" cy="50" r="40" style="fill:red;"/> <circle class ="circle1" onclick="function()" cx="50" cy="150" r="40" style="fill:red;"/> <circle class ="circle1" onclick="function()" cx="50" cy="250" r="40" style="fill:red;"/> <circle class="circle1" onclick="function()" cx="50" cy="350" r="40" style="fill:red;"/> <circle class="circle1" onclick="function()" cx="50" cy="450" r="40" style="fill:red;"/> <circle class ="circle1" onclick="function()" cx="50" cy="550" r="40" style="fill:red;"/> <circle class="circle1" onclick="function()" cx="50" cy="650" r="40" style="fill:red;"/> </svg>而不使用DENSE_RANK()子句,例如:

PARTITION BY

答案 1 :(得分:1)

使用rank()

SELECT
            rownum = rank() OVER (ORDER BY Number),
            Number
        FROM #SEQNUMBERSTEMP
相关问题