我正在考虑从表格中的多个行(与特定的产品ID和类型匹配)更新item number
列,但我想在“Seqnumber”列中按数字排序行项目编号列从1开始,按顺序计数每一行。
使用下面的代码我已经能够选择我想要的产品ID和类型,并按顺序增加值更新项目编号列,但是我不知道如何订购所需的行?
DECLARE @id nvarchar(6)
SET @id = 0
UPDATE Table1
SET @id = Table1.ItemNumber = @id + 1
WHERE Product = '5486' AND Table1.Type = 'C'
我知道您不能在ORDER BY
命令中使用UPDATE
命令而不将其用作子查询。但是我不确定我应该如何在上面的代码中包含它?
我认为我需要合并下面的代码,但不确定SELECT
语句应该是什么,当我尝试时我无法使其工作?
DECALRE @id nvarchar(6)
SET @id = 0
UPDATE Table1
SET @id = TABLE1.ItemNumber = @id + 1
FROM (SELECT TOP (??)* FROM Table1
WHERE Product = '5486' AND Table1.Type ='C'
ORDER BY Table1.SeqNumber ASC
答案 0 :(得分:1)
您应该能够使用表中所需的值构建CTE并更新CTE
declare @Table1 table (Product varchar(4), [Type] varchar(1), SeqNumber int, ItemNumber int)
INSERT INTO @Table1 VALUES
('5486', 'C', 3, 0),
('5486', 'C', 2, 0);
with cte as (
select *,
ROW_NUMBER() OVER (ORDER BY SeqNumber) rn
from @Table1
where Product = '5486' and Type ='C'
)
Update cte
set ItemNumber = rn
答案 1 :(得分:0)
这应该有效:
SET @id = 0;
UPDATE Table1
SET @id = Table1.ItemNumber = (@id := @id + 1)
WHERE Product = 5486 and Table1.Type = 'C'
ORDER BY Table1.seqnumber;
您无法将ORDER BY
与JOIN
一起使用,因此您需要在update
之前初始化变量。
答案 2 :(得分:-1)
UPDATE sales_data
SET ID = ID + 1
ORDER BY ID DESC;