有Cancelled
一行的产品由以下给出:
select distinct productid from tbl where status='Cancelled'
这些的最大行号是:
select productid,max(lineno) n from tbl
where productid in (select distinct productid from tbl where status='Cancelled')
group by productid
对应startdate
的由下式给出:
select a.productid pid,b.n,a.startdate d from tbl a
join (
select productid,max(lineno) n from tbl
where productid in (
select distinct productid from tbl
where status='Cancelled'
)
group by productid
)b on (a.productid=b.productid and a.lineno=b.n)
最后,要tbl
根据此更新,您应该:
update tbl set enddate=d
from (
select a.productid pid,b.n,a.startdate d from tbl a
join (
select productid,max(lineno) n from tbl
where productid in (
select distinct productid from tbl
where status='Cancelled'
)
group by productid
)b on (a.productid=b.productid and a.lineno=b.n)
) t
where productid=t.pid
如果您只需要相关lineno
更新的行,请添加and lineno=t.n
到where
子句中。