在sql server中追加rowNumber()的最大值

时间:2018-03-15 20:38:18

标签: sql-server

您好我正在处理一个要求,我正在使用rownumber()函数来获取当我在文件中插入第一批行时工作正常的亚麻,但问题是当我插入新批处理时Id,行号从1开始。我想继续从Id的最大值开始,如下所示

对于第一批行插入

OrderID   Row#   ConfirmationID
---------  ----  -------------
258584048   1   285477904
258584048   2   285477905
258584048   3   285477907
258584048   4   285477908 

对于Secon批次的行再次插入,它从1开始

OrderID   Row#   ConfirmationID
---------  ----  -------------
258584048   1   285477911
258584048   2   285477912
258584048   3   285477913
258584048   4   285477914

我期待结果如下

OrderID   Row#   ConfirmationID
---------  ----  -------------

258584048   1   285477904
258584048   2   285477905
258584048   3   285477907
258584048   4   285477908 
258584048   5   285477911
258584048   6   285477912
258584048   7   285477913
258584048   8   285477914

row_number() over(PARTITION BY OrderID order by OrderID)

2 个答案:

答案 0 :(得分:0)

这有点奇怪,但你可以这样做。

row_number() over(PARTITION BY OrderID order by OrderID) + (select max(OrderID) from YourTable where OrderID = [YourInsertingOrderID])

答案 1 :(得分:0)

如果您同时输入多个订单ID,只需扩展Sean答案:

countDownTimer = new CountDownTimer(activityDuration, 1000) {
        @Override
        public void onTick(long timeLeftInMillis) {
            int minutes = (int) (timeLeftInMillis / 1000) / 60;
            int seconds = (int) (timeLeftInMillis / 1000) % 60;

            String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
            countDownTimerTextView.setText(timeLeftFormatted);

            System.out.println("L: " + timeLeftInMillis); // Returns correctly. Values between 0 and 60000
            System.out.println("Activity Duration: " + activityDuration); // Returns correctly. 60000
            System.out.println("Progress: " + (timeLeftInMillis / activityDuration) * 100); // Returns 0
        }

        @Override
        public void onFinish() {

        }
    }.start();

另外,我修改了INSERT INTO yourtable(OrderID, Row, ConfirmationID) SELECT yst.OrderId , row_number() over(PARTITION BY yst.OrderID order by yst.ConfirmationID) + ISNULL(xt.maxByOrder, 0) , yst.ConfirmationId FROM yourSourceTable yst LEFT OUTER JOIN ( select max(yt.Row) as maxByOrder, yt.OrderID from yourtable yt group by yt.OrderId ) xt ON xt.OrderId = yst.OrderId WHERE... -- Filter in your source table to get the records you want to insert 函数的ORDER BY,因为当ROW_NUMBER已经按OrderId进行分区时,OrderId排序不执行任何操作。我已将ConfirmationID设置为订购字段,但如果不符合您的要求,请随时更改。

更进一步,如果你有一个过滤器,你可以改进子查询,只返回你将要在表中插入的记录中包含的那些订单的最大值。