SQL查询 - 使用同一个表中的记录值更新现有的字段

时间:2013-11-25 05:21:55

标签: sql sql-server sql-server-2012

环境:SQL Server 2012

我有一个事务表,其中包含一组具有组ID列的记录。

在下面的示例中,组2记录是从组1记录中复制的,除了sideId,sideSort,topId和topSort列。有没有办法将其从第1组级联到第2组for just topSort and sideSort?困难的部分是topId和sideId因父表中的Identity字段而不同。

这是sqlfiddle of the example

enter image description here

3 个答案:

答案 0 :(得分:1)

你可以这样做。这是基于您将一个组(@copiedFromGroupId)的所有记录复制到另一个组(@copiedToGroupId)的假设,即ID将被移动第一组中的记录数。 / p>

declare @copiedFromGroupId int = 1
declare @copiedToGroupId int = 2
declare @shift int

select @shift = (select max(id) from Tracker where GroupId = @copiedToGroupId) 
  - (select max(id) from Tracker where GroupId = @copiedFromGroupId)

UPDATE T1
SET 
  T1.TopSort = T2.TopSort,
  T1.SideSort = T2.SideSort
FROM Tracker T1
INNER JOIN Tracker T2 ON T1.ID = T2.ID + @shift

选中此SQL Fiddle

答案 1 :(得分:1)

这是基于TopId和SortID列的ORDER上的row_number:

update test
set test.topSort = mix.topSort, test.sideSort = mix.sideSort
from
(select a.groupid aGroupid, b.groupID, b.Id bID, a.topSort, a.sideSort
from (select groupid, 
     row_number() over(order by topID, sideId) rn,
     topSort, sideSort,
     id
     from test where groupid=1) a
inner join  
     (select groupid, 
     row_number() over(order by topID, sideId) rn,
     topSort, sideSort,
     id
     from test where groupid=2) b ON a.rn = b.rn) mix
inner join test on test.id=mix.bId
WHERE test.groupid=2;

SQLFiddle

答案 2 :(得分:0)

假设Id是组中的订单字段:

WITH C as 
(
  select Tracker.*,
    ROW_NUMBER() OVER (PARTITION BY GroupId ORDER BY Id) as RN
  FROM Tracker  
)  
UPDATE CT 
SET CT.topSort=CTU.topSort,
    CT.sideSort=CTU.sideSort

FROM C as CT
JOIN C as CTU ON (CT.rn=CTU.rn) 
                  and (CTU.GroupID=1)
WHERE CT.GroupID=2

SQLFiddle demo