我有下表:
Id CategoryId Code Status
=================================
1 A100 0012 NULL
2 A100 0012 NULL
3 A100 0055 NULL
4 A100 0012 NULL
5 B201 1116 NULL
6 B201 1116 NULL
7 B201 1121 NULL
8 B201 1024 NULL
逻辑:1。对于相同的CategoryID,代码应该相同。 2.如果存在多个代码,请考虑具有最低值的代码。
期望的结果:
Id CategoryId Code Status
=================================
1 A100 0012 NULL
2 A100 0012 NULL
3 A100 0055 FAIL
4 A100 0012 NULL
5 B201 1116 FAIL
6 B201 1116 FAIL
7 B201 1121 FAIL
8 B201 1024 NULL
由于
答案 0 :(得分:0)
按照您的编辑...
DECLARE @T TABLE
(
ID INT,
CategoryID CHAR(4),
Code CHAR(4),
Status CHAR(4) NULL
)
INSERT INTO @T (ID,CategoryID, Code)
SELECT 1,'A100',0012 UNION ALL SELECT 2,'A100',0012 UNION ALL
SELECT 3,'A100',0055 UNION ALL SELECT 4,'A100',0012 UNION ALL
SELECT 5,'B201',1116 UNION ALL SELECT 6,'B201',1116 UNION ALL
SELECT 7,'B201',1121 UNION ALL SELECT 8,'B201',1024;
WITH T AS
(
SELECT *, MIN(Code) OVER (PARTITION BY CategoryID ) AS MinCode
from @T
)
UPDATE T
SET Status = 'FAIL'
WHERE Code <> MinCode
SELECT *
FROM @T
返回
ID CategoryID Code Status
----------- ---------- ---- ------
1 A100 12 NULL
2 A100 12 NULL
3 A100 55 FAIL
4 A100 12 NULL
5 B201 1116 FAIL
6 B201 1116 FAIL
7 B201 1121 FAIL
8 B201 1024 NULL
答案 1 :(得分:0)
我会采取刺,但我真的认为这应该是一个新问题。
;WITH o AS
(
SELECT Id, CategoryId, Code, Status,
rn = ROW_NUMBER() OVER (PARTITION BY CategoryId ORDER BY Id)
FROM dbo.my_table
),
n AS
(
SELECT CategoryId, Code
FROM o WHERE rn = 1
)
UPDATE o
SET [Status] = 'FAILURE'
FROM o INNER JOIN n
ON o.CategoryId = n.CategoryId
AND o.Code <> n.Code
WHERE o.rn > 1;