大家好!最近在做项目时碰到一个问题,一直找不到好的方法解决。
表A如下:
Year_Mon Com_1 Val_1 Com_2 Val_2 Com_3 Val_3 Com_4 Val_4 Com_5 Val_5
200804            c1 100 c2 200 c3 300 c4 400 c5 500
200804            c1 101 c2 201 c3 301 c4 401 c5 501
200804            c1 102 c2 202 c3 302 c4 402 c5 502
200805            c1 103 c2 203 c3 303 c4 403 c5 503
200805            c1 104 c2 204 c3 304 c4 404 c5 504
200805            c1 105 c2 205 c3 305 c4 405 c5 505
表B如下:
Year_Mon Com
200803         c3
200803         c5
200804         c2
200804         c3
200805         c3
200805         c4
200805         c5A表和B表通过Year_Mon字段关联.
其中,A表的Com1、Com2、Com3、Com4、Com5字段 分别去B表的Com中遍历。
如果在同一时间内,Com1中内容不存在于B表的COM中。则A表该COM1的相关字段内容为空。
例如:
 200804时刻, B表的COM中只有C2、C3 
 200805时刻,B表的COM中只有C3、C4、C5
则A表的内容应该变为:Year_Mon      Com_1    Val_1   Com_2   Val_2   Com_3   Val_3  Com_4    Val_4  Com_5  Val_5
200804          0 c2 200 c3 300 0 0
200804          0 c2 201 c3 301 0 0
200804          0 c2 202 c3 302 0 0
200805          0 0 c3 303 c4 403 c5 503
200805          0 0 c3 304 c4 404 c5 504
200805          0 0 c3 305 c4 405 c5 505
我现在想到的方法很土的,就是每次A表中选一个字段和B表COM字段 去遍历对比。这样就需要对比5次,
COM1 和 COM ,COM2 和 COM ,COM3 和 COM ,COM4 和 COM ,COM5 和 COM 。
如果A表中存在十几个字段需要去和COM对比,这样就非常麻烦了。请问大家有什么好方法,小弟不胜感激。谢谢。

解决方案 »

  1.   

    select a.year_mon,
      nvl(b.com_1,0)com_1,
      decode(b.com_1,'c1',val_1,0)val_1,
      nvl(b.com_2,0)com_2,
      decode(b.com_2,'c2',val_2,0)val_2,
      nvl(b.com_3,0)com_3,
      decode(b.com_3,'c3',val_3,0)val_3,
      nvl(b.com_4,0)com_4,
      decode(b.com_4,'c4',val_4,0)val_4,
      nvl(b.com_5,0)com_5,
      decode(b.com_5,'c5',val_5,0)val_5 from
    aa a left join  (
      select year_mon,
        max(decode(com,'c1','c1'))com_1,
        max(decode(com,'c2','c2'))com_2,
        max(decode(com,'c3','c3'))com_3,
        max(decode(com,'c4','c4'))com_4,
        max(decode(com,'c5','c5'))com_5 from bb
      group by year_mon  )b
    on a.year_mon =b.year_mon
    order by a.year_mon
      

  2.   

    多谢狂浪解答我2个问题。呵呵。
    不过小弟菜鸟始终不明白 sql中的'c1'、'c2'、'c3' 的意思。这些是字段中的实际内容吗?
    如果是的话,字段的内容是改变的啊。硬编码在sql中,如果内容改变了怎么办呢?
      

  3.   

    狂浪兄,请问sql中的aa  和  bb  是否就是我的原表A和B。
    另外,我按你的sql测试,发现得出的结果不对啊。