根据您的要求,我提供了以下内容。
- 第一个更新会进行必要的重置。
AcctLevel1
每当上一行发生更改时,第二个原因为 1。
- 第三次更新总结了这些 1 以创建最终结果。
数据:
create table data
(
id int,
CatLevel1 varchar(5),
AcctLevel1 varchar(5)
);
insert into data values (0,'1','0');
insert into data values (1,'2','0');
insert into data values (2,'1','1');
insert into data values (3,'2','1');
insert into data values (4,'2','1');
SQL 命令:
UPDATE `data` t1 SET AcctLevel1 = 0;
update `data` t1
left outer JOIN `data` t2
on t1.id-1 = t2.id
set t1.AcctLevel1 =
case when t1.CatLevel1 = t2.CatLevel1 then t1.AcctLevel1
else t2.AcctLevel1+1 end;
update `data` t1
set t1.AcctLevel1 =
( select SUM(TEMP.AcctLevel1) from (SELECT *FROM `data`) AS TEMP where TEMP.ID <= t1.ID );
更新:最终玩具查询
UPDATE `data` t4
SET AcctLevel1 =
(
SELECT CASE WHEN TEMP.SCHANGES IS NULL THEN 0 ELSE TEMP.SCHANGES END from
(SELECT T3.ID,
(SELECT SUM(CASE WHEN t1.CatLevel1 = t2.CatLevel1 THEN 0 ELSE 1 END) AS SUM_CHANGES
FROM `data` t1,
`data` t2
WHERE t1.id-1 = t2.id
AND t1.ID <= t3.ID) AS SCHANGES
FROM `DATA` t3 ) as TEMP where TEMP.ID = T4.ID
);
最终的 JSFiddle: http ://sqlfiddle.com/#!2/325f16/2