我有一张这样的表
ID Group
----------- -----------
2 NULL
4 NULL
7 NULL
8 NULL
11 NULL
12 NULL
我想根据行号更新我的表
ID Group
----------- -----------
2 G_1
4 G_1
7 G_2
8 G_2
11 G_3
12 G_3
前N行---> G_1,
N + 1到2N行---> G_2,
2N + 1至3N行---> G_3。
...
我怎样才能实现这个目标?
提前致谢。
答案 0 :(得分:2)
假设您使用的是SQL 2005或更高版本:
DECLARE @n integer
SELECT @N = 3;
WITH rows AS
(
SELECT
ID,
ROW_NUMBER() OVER (ORDER BY ID) RowNum
FROM temp
)
UPDATE temp
SET [Group] = 'G_' + CONVERT(VARCHAR(4),((RowNum-1) / @N) + 1)
FROM temp
INNER JOIN rows ON temp.ID = rows.ID
答案 1 :(得分:2)
DECLARE @n INT
SET @n = 5
UPDATE my_table
SET [Group] = 'G_' + CAST((row_nums.row_num / (@n + 1)) + 1 AS VARCHAR)
FROM
(SELECT
my_table.ID,
my_table.[Group],
ROW_NUMBER() OVER (ORDER BY my_table.ID) row_num
From my_table
) row_nums
WHERE row_nums.ID = my_table.ID
答案 2 :(得分:2)
declare @N int = 2
declare @t table(ID int, Grp char(3))
insert @t(id) values(2),(4),(7),(8),(11),(12)
;with x as
(
select id, Grp,
(row_number() OVER(ORDER BY ID)+1) / @N rn
from @t
)
update x
set grp = 'G_' + cast(rn as varchar(9))
select * from @t
结果:
ID Grp
2 G_1
4 G_1
7 G_2
8 G_2
11 G_3
12 G_3
答案 3 :(得分:0)
为什么要更新?存储计算值的形式很差。如果您的ID将来必须更改,会发生什么? (如果它是主键,那真的不应该,但我生活在现实生活中的真实世界。)
SELECT id,
CASE
WHEN id <= n and id > 2*n then 'G_' + '1'
WHEN id <= 2*n and id > 3*n then 'G_' + '2'
WHEN id < 3*n then 'G_' + '3'
END AS GROUP
根据您的目的,您可以将其放入视图或计算列中。