[英]Update the Column values as grouped Sequence number based on input number provided in sql server
I want to update batch column here我想在这里更新批处理列
ID CustId Batch
1 100 NULL
2 101 NULL
3 102 NULL
4 103 NULL
5 104 NULL
6 105 NULL
7 106 NULL
8 107 NULL
9 108 NULL
10 109 NULL
11 110 NULL
Based on the input number provided, lets say I have input 2. Logic here is Divide the Number of records by input number.根据提供的输入编号,假设我输入了 2。这里的逻辑是将记录数除以输入编号。 In this case it becomes 11/2 =5.5
在这种情况下,它变成 11/2 =5.5
The result should look like below结果应该如下所示
ID CustId Batch
1 100 1
2 101 1
3 102 2
4 103 2
5 104 3
6 105 3
7 106 4
8 107 4
9 108 5
10 109 5
11 110 6
Please suggest an sql query for this.请为此建议一个 sql 查询。
One method is:一种方法是:
select t.*,
ntile(ceiling(cnt / @n)) over (order by id) as batch
from (select t.*, count(*) over () as cnt
from t
) t;
Another method is:另一种方法是:
select t.*,
floor( (row_number() over (order by id) - 1) / n) as batch
from t;
The below code will generate the required result.下面的代码将生成所需的结果。 The reason for taking @input as DECIMAL is, it will consider the decimal values and not just round of to the INT value.
将@input 设为 DECIMAL 的原因是,它会考虑十进制值,而不仅仅是四舍五入到 INT 值。
DECLARE @input DECIMAL = 2;
WITH CTE AS (
SELECT t.ID, ROW_NUMBER() OVER (ORDER BY ID) AS rowNo
FROM Table t
)
UPDATE t
SET Batch = CEILING( c.rowNo / @input)
FROM Table t
INNER JOIN CTE c
ON t.ID = c.ID
To check the output before running Update
-- DECLARE @input DECIMAL = 2
-- SELECt t.*, CEILING( ROW_NUMBER() OVER (ORDER BY ID) / @input) as NewBatch
-- FROM
-- Table t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.