我有一个导入过程,需要更新表中旧记录的“结束日期”。导入来自其他人,我需要一些与特定用户信息匹配的细节。我需要做的是更新旧记录,在下面的示例中,该记录将是UserID = 1
,而不是更新UserID = 4
。
我有以下sql要更新,但正如你所知,它会更新两个记录:
UPDATE t1
SET t1.[EndDate] = t2.[EndDate]
FROM ExistingUser AS t1, ImportUser AS t2
WHERE (t2.[uName] = t1.[uName]) AND (t1.[EndDate] IS NULL);
免责声明:我没有创建数据库,也无法重新设计表格,所以请怜悯我。感谢!!!
ExistingUser - 表
UserID uName BeginDate EndDate
1 John 01/01/2013
2 Mary 05/01/2014 04/30/2015
3 Bob 12/01/2014
4 John 06/01/2015
ImportUser - 表
uName EndDate
John 05/31/2015
答案 0 :(得分:2)
这可以通过构建一个子查询来完成,该子查询使用没有填充EndDate
的用户名对条目进行编号。这个子查询看起来像这样:
SELECT [UserID], [uName],
ROW_NUMBER() OVER (PARTITION BY [uName] ORDER BY [BeginDate]) AS IX
FROM ExistingUser
WHERE [EndDate] IS NULL
演示:http://www.sqlfiddle.com/#!6/72c49/2
| UserID | uName | IX |
|--------|-------|----|
| 3 | Bob | 1 |
| 1 | John | 1 |
| 4 | John | 2 |
在此子查询中,具有相同uName
John
的两个记录按BeginDate
顺序编号。现在,如果我们将原始UPDATE
查询加入此子查询中搜索IX=1
的记录,我们将只更新最早的行。
WITH EarliestExistingUser AS (
SELECT [UserID], [uName],
ROW_NUMBER() OVER (PARTITION BY [uName] ORDER BY [BeginDate]) AS IX
FROM ExistingUser
WHERE [EndDate] IS NULL
)
UPDATE t1
SET t1.[EndDate] = t2.[EndDate]
FROM ExistingUser AS t1
JOIN EarliestExistingUser AS t1f ON t1.UserID = t1f.UserID
,ImportUser AS t2
WHERE (t2.[uName] = t1.[uName]) AND (t1.[EndDate] IS NULL)
AND (t1f.IX = 1)