我想交换表中两行的值.我有两行的行ID.有没有查询呢?这是一个例子.在查询之前我有这个:
row1 : 1,2,3 row2 : 5,6,7
交换后我想要这个:
row1 : 5,6,7 row2 : 1,2,3
如果要将两个已知ID的值从一行交换到另一行,请尝试以下操作:
--need to store the original values
SELECT
*,CASE WHEN id=123 then 987 ELSE 123 END AS JoinId
INTO #Temp
FROM YourTable
WHERE ID in (123,987)
--swap values
UPDATE y
SET col1=t.col1
,col2=t.col2
FROM YourTable y
INNER JOIN #Temp t ON y.id =t.JoinId
WHERE ID in (123,987)
Run Code Online (Sandbox Code Playgroud)
如果您只需要交换几行,那么您可以使用定制的 case 语句和连接,就像其他答案中一样。如果你需要对很多行进行操作,那会很痛苦。在这种情况下,我建议使用映射表。
WITH map AS (
SELECT *
FROM (VALUES
(1, 2), -- Here's an example of swapping two rows:
(2, 1), -- 1 <- 2, 2 <- 1
(3, 4), -- Here's an example of rotating three rows:
(4, 5), -- 3 <- 4, 4 <- 5, 5 <- 3
(5, 3),
(6, 7) -- Here's an example of just copying one row to another: 3 <- 5
) AS a (destID, srcID)
)
UPDATE destination
SET
ColumnA = source.ColumnA,
ColumnB = source.ColumnB,
ColumnC = source.ColumnC
FROM
SomeTable AS destination
JOIN map ON map.destID = destination.ID
JOIN SomeTable AS source ON source.ID = map.srcID
Run Code Online (Sandbox Code Playgroud)
笔记
简单的更新工作:
UPDATE myTable
SET
col1 = CASE WHEN col1 = 1 THEN 5 ELSE 1 END,
col2 = CASE WHEN col2 = 2 THEN 6 ELSE 2 END,
col3 = CASE WHEN col3 = 3 THEN 7 ELSE 3 END
Run Code Online (Sandbox Code Playgroud)
结果:行值被交换。
| 归档时间: |
|
| 查看次数: |
36005 次 |
| 最近记录: |