Sql 用max更新语句

Sql 用max更新语句,sql,Sql,我的桌子看起来像 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

我的桌子看起来像

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
感谢

取消了
行的产品如下所示:

select distinct productid from tbl where status='Cancelled'
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)
这些设备的最大行号为:

select productid,max(lineno) n from tbl
where productid in (select distinct productid from tbl where status='Cancelled')
group by productid
相应的
startdate
如下所示:

select distinct productid from tbl where status='Cancelled'
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
的行,请将
和lineno=t.n
添加到
where
子句中。

您使用的是什么RDBMS?是否还要删除其他行?首先尝试编写
SELECT
语句,该语句将返回所需的结果,然后只需将
SELECT
语句修改为
UPDATE
。如果
productId 1
StartDate为max(linenumber),您是如何获得
02/04/2006
?使用sql server。ProductId 1的结束日期应为2003年10月25日您需要更新特定产品的所有行,还是只需要取消
行?