如果ItemCode,Color,Size,Rack,Rack1匹配,那么Num列需要采用增量值而不是NULL。这意味着对于突出显示的行,它需要取值1
和2
,而对于其他(非重复)记录,则需要取值1
。
答案 0 :(得分:0)
表架构:
CREATE TABLE Items
(
ItemCode VARCHAR(10),
Color INT,
Size VARCHAR(10),
Rack VARCHAR(10),
RACK1 INT,
NUM INT
)
数据:
INSERT INTO Items VALUES
('LY-164', 1, 'L', 'LT', 74, NULL),
('LY-164', 1, 'M', 'LT', 75, NULL),
('LY-164', 1, 'XL', 'LT', 67, NULL),
('LY-164', 1, 'XXL', 'LT', 70, NULL),
('LY-178', 1, 'L', 'LT', 104, NULL),
('LY-178', 1, 'L', 'LT', 109, NULL),
('LY-178', 1, 'M', 'LT', 122, NULL),
('LY-178', 1, 'M', 'LT', 122, NULL),
('LY-178', 1, 'XL', 'LT', 108, NULL),
('LY-178', 1, 'XL', 'LT', 109, NULL),
('LY-178', 1, 'XXL', 'LT', 108, NULL)
如果您的表中没有主键,则可以使用此键。这里我先插入然后删除空值。
; WITH CTE AS
(
SELECT ItemCode, Color, Size, Rack, Rack1
, ROW_NUMBER() OVER (PARTITION BY ItemCode, Color, Size, Rack, Rack1 ORDER BY ItemCode, Color, Size, Rack, Rack1) AS RN
FROM Items
)
INSERT INTO Items
SELECT * FROM CTE
DELETE FROM Items WHERE NUM IS NULL
SELECT * FROM Items
这是另一种方法(Quirky Update,SQL中的黑魔法之一)
DECLARE @ItemCode VARCHAR(10)
DECLARE @Color INT
DECLARE @Size VARCHAR(10)
DECLARE @Rack VARCHAR(10)
DECLARE @RACK1 INT
DECLARE @NUM INT = 1
UPDATE A
SET
@NUM = IIF(@ItemCode IS NULL OR @ItemCode <> A.ItemCode OR @Color <> A.Color OR @Size <> A.Size OR @Rack <> A.Rack OR @RACK1 <> A.RACK1, 1, @Num + 1),
@ItemCode = A.ItemCode,
@Color = A.Color,
@Size = A.Size,
@Rack = A.Rack,
@RACK1 = A.RACK1,
A.Num = @NUM
FROM Items A
SELECT * FROM Items
答案
LY-164 1 L LT 74 1
LY-164 1 M LT 75 1
LY-164 1 XL LT 67 1
LY-164 1 XXL LT 70 1
LY-178 1 L LT 104 1
LY-178 1 L LT 109 1
LY-178 1 M LT 122 1
LY-178 1 M LT 122 2
LY-178 1 XL LT 108 1
LY-178 1 XL LT 109 1
LY-178 1 XXL LT 108 1