如下表:
STCD              ZA   ZB
0100101 10   NULL
0100102 NULL 13
0100201 15   NULL
0100202 NULL 10 只有 substring(STCD,6,2)='01' 的情况下才有ZA的值,
只有 substring(STCD,6,2)='02' 的情况下才有ZB的值。现在想把 left(STCD,5) 相同的纪录取出,而且要把 substring(STCD,6,2)='01' 的 ZA 值要插入到 substring(STCD,6,2)='02' 的 ZA 中,然后去掉 substring(STCD,6,2)='01'的行,最终结果:STCD        ZA    ZB
01001       10    13
01002    15    10 请教各位这样的sql该怎么写?

解决方案 »

  1.   

    select STCD,case WHEN substring(STCD,6,2)='01' then ZA ELSE ZB end as [ZA/ZB] from tableName
      

  2.   

    select STCD,(select ZA from t where left(STCD,5)= t1.STCD and ZA>0) as ZA ,(select ZB from t where left(STCD,5)= t1.STCD and ZB>0) as ZB 
    from (select DISTINCT left(STCD,5) as STCD from t) as t1
      

  3.   

    try
    -------------------------------------
    declare @t table
    (STCD varchar(10),ZA int,ZB int)insert into @t
    select '0100101',10,NULL union all
    select '0100102',NULL,13 union all
    select '0100201',15,NULL union all
    select '0100202',NULL,10--select  * from @tselect left(STCD,5),ZA,ZB=(select ZB from @t where STCD=left(a.STCD,5)+'02') from @t a
    where not za is null
      

  4.   

    select STCD,case WHEN substring(STCD,6,2)='01' then ZA ELSE ZB end as [ZA/ZB] from tableName
    不行得到的是0100101 10
    0100102 13
    0100201 15
    0100202 10
    而不是
    01001 10 13
    01002 15 10
      

  5.   

    select left(STCD,5),ZA,ZB=(select ZB from t where STCD=left(a.STCD,5)+'02') from t a
    where not za is null
    这个是对的,比我写的简单些
      

  6.   

    select left(STCD,5),ZA=Max(case substring(STCD,6,2) when '01' then ZA END),ZB=Max(case substring(STCD,6,2) when '01' then ZB END)
    from tableName
    group by left(STCD,5)
    没看清楚,不好意思.
      

  7.   

    ZB=Max(case substring(STCD,6,2) when '02' then ZB END)//改下,when '02'