我正在使用SQL Server2017。我需要帮助,以匹配条件为基础,用同一表中不同行中的值设置行中的值。
请看下面的结果屏幕截图,应将“ TaskHeaderKey”中突出显示的“ 0”设置为“ 332807”的“ TaskKey”值。当“ TaskNumber”中的值中没有“-”与所有其他行中的“ 之前” 中的值匹配时,就会发生这种情况。如您所见,我只能通过将“ TaskHeaderKey”设置为“ TaskKey”(其中“ TaskNumber”不包含“-”)来完成部分工作。
这是我到目前为止的代码:
UPDATE tt1
SET tt1.TaskHeaderKey = tt2.TaskKey
FROM Task tt1
INNER JOIN Task tt2 ON tt1.TaskKey = tt2.TaskKey
INNER JOIN Project pj ON tt1.ProjectKey = pj.ProjectKey
WHERE pj.IntelTIProject = 1 AND pj.ProjectOpen = 1
AND (IIf(charindex('-', tt1.TaskNumber) = 0, tt1.TaskNumber, Left(tt1.TaskNumber, charindex('-', tt1.TaskNumber) - 1)) = tt2.TaskNumber)
AND ISNUMERIC(Left(tt2.TaskNumber, 1)) = 1
AND tt1.ProjectKey = tt2.ProjectKey
编辑 根据公认的答案,这是我使用的:
UPDATE td1
SET td1.TaskHeaderKey = tdx.TaskKey
FROM
Task td1
CROSS APPLY (
SELECT top (1)
td2.TaskKey
FROM
Task td2
INNER JOIN Project pj ON td2.ProjectKey = pj.ProjectKey
WHERE
td1.ProjectKey = td2.ProjectKey
AND pj.IntelTIProject = 1
AND pj.ProjectOpen = 1
AND td1.TaskNumber LIKE td2.TaskNumber + '%'
AND td2.TaskNumber NOT LIKE '%-%'
AND ISNUMERIC(Left(td2.TaskNumber, 1)) = 1
) tdx
WHERE
td1.taskheaderkey = 0;
答案 0 :(得分:2)
这看起来会为您提供所需的结果。
IF OBJECT_ID('tempdb..#TestData', 'U') IS NOT NULL
BEGIN DROP TABLE #TestData; END;
CREATE TABLE #TestData (
taskkey INT NOT NULL,
tasknumber VARCHAR(10) NOT NULL,
taskheaderkey INT NOT NULL,
productkey INT NOT NULL
);
INSERT #TestData (taskkey, tasknumber, taskheaderkey, productkey) VALUES
(332807, '091', 332807, 2710),
(405311, '091-0099', 0, 2710);
--================================================
UPDATE td1 SET
td1.taskheaderkey = tdx.taskkey
FROM
#TestData td1
CROSS APPLY (
SELECT top (1)
td2.taskkey
FROM
#TestData td2
WHERE
td1.productkey = td2.productkey
AND td1.tasknumber LIKE td2.tasknumber + '%'
AND td2.tasknumber NOT LIKE '%-%'
) tdx
WHERE
td1.taskheaderkey = 0;