也许您可以尝试使用变量:
SQLFIDDLE 演示
set @sku:='';
select a.rid, a.id,
@sku:= (case when @sku<>a.sku
then a.sku else 'updated'
end) as skus, @sku:=a.sku, a.name
from skus a
;
| RID | ID | SKUS | @SKU:=A.SKU | NAME |
-----------------------------------------------------
| 1 | 3 | rs-123 | rs-123 | test product |
| 2 | 3 | updated | rs-123 | test product |
| 3 | 4 | rs-125 | rs-125 | test product 2 |
| 4 | 4 | updated | rs-125 | test product 2 |
| 5 | 4 | updated | rs-125 | test product 2 |
| 6 | 6 | rs-126 | rs-126 | test product 3 |
对于更新:
用于更新的 SQLFIDDLE 演示
set @sku:='';
UPDATE
skus a
join
(select a.rid, a.id,
@sku:= (case when @sku<>a.sku
then a.sku else 'updated'
end) as skus, @sku:=a.sku, a.name
from skus a) b
on a.rid = b.rid
SET
a.sku = 'up_again'
WHERE
b.skus = 'updated'
;
| RID | ID | SKU | NAME |
----------------------------------------
| 1 | 3 | rs-123 | test product |
| 2 | 3 | up_again | test product |
| 3 | 4 | rs-125 | test product 2 |
| 4 | 4 | up_again | test product 2 |
| 5 | 4 | up_again | test product 2 |
| 6 | 6 | rs-126 | test product 3 |
这是另一个使用Joins
:
http://sqlfiddle.com/#!2/ddf47/2
update skus a
join skus b
on a.rid = b.rid +1
set a.sku = 'updated'
where a.sku = b.sku
;
| RID | ID | SKU | NAME |
---------------------------------------
| 1 | 3 | rs-123 | test product |
| 2 | 3 | updated | test product |
| 3 | 4 | rs-125 | test product 2 |
| 4 | 4 | updated | test product 2 |
| 5 | 4 | updated | test product 2 |
| 6 | 6 | rs-126 | test product 3 |
要同时更新 sku 和名称:
http://sqlfiddle.com/#!2/97f4f/1
update skus a
join skus b
on a.rid = b.rid +1
set a.sku = 'updated', a.name = 'new_name'
where a.sku = b.sku
;
| RID | ID | SKU | NAME |
---------------------------------------
| 1 | 3 | rs-123 | test product |
| 2 | 3 | updated | new_name |
| 3 | 4 | rs-125 | test product 2 |
| 4 | 4 | updated | new_name |
| 5 | 4 | updated | new_name |
| 6 | 6 | rs-126 | test product 3 |
在 SQL SERVER 中使用 ROW_NUMBER() 查看 OP 的问题
http://sqlfiddle.com/#!3/355c4/2
update a
set a.sku = 'updated', a.name = 'new_name'
from skus a
join (Select rid, id, row_number() over (
partition by id order by rid asc) rank
from skus) b
on a.rid = b.rid
where b.rank > 1
;
| RID | ID | SKU | NAME |
---------------------------------------
| 1 | 3 | rs-123 | test product |
| 2 | 3 | updated | new_name |
| 3 | 4 | rs-125 | test product 2 |
| 4 | 4 | updated | new_name |
| 5 | 4 | updated | new_name |
| 6 | 6 | rs-126 | test product 3 |