在列中具有共享值的两行之间交换值



我在SQL Server表中有如下数据:

Name         D/C       Code
Expenses     Debit     10000 
Expenses     Credit    20000
Transport    Debit     50000 
Transport    Credit    60000

我想像这样交换代码列值:

Name       D/C       Code
Expenses   Debit     20000
Expenses   Credit    10000
Transport  Debit     60000
Transport  Credit    50000

有没有办法使用 SQL UPDATE 命令来执行此操作?

如果您有身份列 试试这个

update t1 
set
t1.code=t2.code
from your_table as t1 inner join your_table as t2
on t1.name=t2.name
where t1.[D/c]='Debit' and t2.[D/c]='Credit' and t1.id_col=t2.id_col-1

最新更新