有一个表,记录如下:
itemcode   lot    Kind    Status
  A         01     YP        
  A         01     CP       合格
  B         02     YP        
  B         03     CP       不合格
要求将同itemCode,同lot的Kind=‘CP’的记录的Status字段值更新到同itemCode,同lot的Kind=‘YP’的记录的Status字段中,
更新后该表记录为:
itemcode   lot    Kind    Status
  A         01     YP       合格 
  A         01     CP       合格
  B         02     YP       不合格
  B         03     CP       不合格
请问各位,如果用一句SQL写的话,该怎么写呢?想了一上午了,可还是没想出来,谢谢大家。

解决方案 »

  1.   

    update a
    set a.Status = b.Status
    from 表 a join 表 b on a.itemcode = b.itemcode and a.lot = b.lot
    where a.Kind = 'YP' and b.Kind = 'CP'
      

  2.   

    update a
    set a.Status = b.Status
    from 表 a 
    join (select * from 表 where Kind = 'CP') b on a.itemcode = b.itemcode and a.lot = b.lot
    where a.Kind = 'YP'
      

  3.   

    ----创建测试数据
    declare @t table(itemcode varchar(10),lot varchar(10),Kind varchar(10),Status varchar(10))
    insert @t
    select   'A',         '01',     'YP',       NULL   union all        
    select   'A',         '01',     'CP',       '合格' union all
    select   'B',         '02',     'YP',       NULL   union all        
    select   'B',         '03',     'CP',       '不合格'----更新
    update a set Status = (select Status from @t where itemcode = a.itemcode and lot = a.lot and Kind = 'CP')
    from @t as a where Kind = 'YP'----查看
    select * from @t/*结果
    itemcode  lot  king  status
    ---------------------------------------
    A          01    YP    合格
    A          01    CP    合格
    B          02    YP    NULL
    B          03    CP    不合格
    */
      

  4.   

    你給的數據不對吧
     B         02     YP       不合格
      B         03     CP       不合格   //這個log未02才對吧
    create table tmpTable ( itemcode  varchar (10) not null, 
                        lot           varchar(10)        null,    
                        Kind       varchar(10)        null,
                        Status      varchar(20)       null)
    insert into tmpTable
    select   'A',         '01',     'YP', null
    union select   'A',         '01',     'CP',       '合格'
    union select   'B',         '02',     'YP',       null 
    union select   'B',         '02',     'CP',       '不合格'
    select * from tmpTable
    ----------------------------------
    update a  set a.Status = b.Status
    from tmpTable a left join tmpTable b on a.itemcode = b.itemcode and a.lot = b.lot
    where a.Kind = 'YP' and b. Kind = 'CP' -----------------------------------
    select * from tmpTable
    ------------------------------------
    drop table tmpTable 
    ---------結果----------------------
    A 01 CP 合格
    A 01 YP 合格
    B 02 CP 不合格
    B 02 YP 不合格
      

  5.   

    update a set Status = (select Status from @t where itemcode = a.itemcode and lot = a.lot and Kind = 'CP')
    from @t as a where Kind = 'YP'