我的表格似乎是
Product Id Status Line N0 startDate ENDdate 1 Ordered 3 01/02/1999 NULL 1 Leased 1 02/04/2006 NULL 1 SubLeased 4 12/31/2000 NULL 1 Cancelled 9 10/25/2003 NULL 2 Deliverd 5 01/02/1999 NULL 2 LOST 3 02/04/2001 NULL 2 Cancelled 4 12/31/2000 NULL
我需要在其中写一个更新语句 如果状态被取消,则产品结束日期为最大起始日期(亚麻布)
结果应该是
ProductId EndDate
1 10/25/2003 Date of line number(9)
2 01/02/1999 Date of line number(5)
由于
答案 0 :(得分:1)
具有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
子句。