表  a ( id ,amount)id    amount2012A  32012B  42011B  32011C  3要的结果:
id    amount2012A  72012B  02011B  62011C  0id 的前4个字符一样的,汇总金额到最后一个字母最前面的那个id上。
请教效率高的sql实现。

解决方案 »

  1.   


    with t(id,amount) as(
    select '2012A',3 from dual
    union all select '2012B',4 from dual
    union all select '2011B',3 from dual
    union all select '2011C',3 from dual
    )
    select id,(case when rn=1 then sum(amount) over(partition by substr(id,1,4)) else 0 end) amount
    from (select row_number() over(partition by substr(id,1,4) order by id) rn,id,amount from t);
    /*
    ID             AMOUNT                                                           
    ---------- ----------                                                           
    2011B               6                                                           
    2011C               0                                                           
    2012A               7                                                           
    2012B               0  
    */
      

  2.   

    是只按照A,B,C 分组吗 不管年份?
      

  3.   

    为什么是from dual,不是from a?
      

  4.   

    如果带年份 直接用id 分组, 只要后面的  就用substr(id,5,4) 进行分组