表数据姓名  月份  工资
---- ---- ----
A     1    10
A     3    20
B     2    30想要得结果是姓名  月份  工资
---- ---- ----
A     1    10
A     2     0
A     3    20
A     4     0
A     5     0
B     1     0
B     2    30
B     3     0
B     4     0
B     5     0也就是说,一个‘姓名’后面一定会有5各月份的数据,如果DB里没有的话,自动补齐(当然,实际中是24个月)

解决方案 »

  1.   

    五张临时表,UNION ALL 一下
      

  2.   

    select T.姓名,T.month 月份,M.工资
    from 
    (select *
    from (select rownum month from all_objects where rownum<=12)a,
    (select distinct 姓名 from 表)b
    )T
    left join 表 M
    on T.姓名=M.姓名 and T.month=M.月份
      

  3.   

    OPER@tl> select * from test;NA      MONTH        PAY
    -- ---------- ----------
    a           1         10
    a           3         20
    b           2         30OPER@tl> select b.names,b.rn,nvl(a.pay,0)
      2  from test a,
      3  (select distinct names,rn
      4  from test,(
      5  select rownum rn from dual connect by rownum<=5)
      6  ) b
      7  where a.month(+)=b.rn
      8  and a.names(+)=b.names
      9  order by b.names,b.rn
     10  /NA         RN NVL(A.PAY,0)
    -- ---------- ------------
    a           1           10
    a           2            0
    a           3           20
    a           4            0
    a           5            0
    b           1            0
    b           2           30
    b           3            0
    b           4            0
    b           5            0已选择10行。OPER@tl> 
      

  4.   

    select an.n,an.b,
    (case when (原表.a is not null and 原表.n=an.n ) then 原表.a else 0 end)
    from 原表,(select am2.n,am1.b,0 a from (select n from 原表 group by n) am2,参数表) an where an.b=原表.b(+) 
    order by an.n,an.b建立一个参数表维护 5个月        月份
    1
    2
    3
    4
    5
    工资表
    工资    月份      姓名
    1 2 A
    2 1 A
    1 3 Bsql 得到结果1 A 1 2
    2 A 2 1
    3 A 3 0
    4 A 4 0
    5 A 5 0
    6 B 1 0
    7 B 2 0
    8 B 3 1
    9 B 4 0
    10 B 5 0
      

  5.   

    确实能实现,谢谢大家能顺便问下,all_objects 这个东东是什么?不太明白,方便的话,能讲解下吗?
      

  6.   

    ALL_OBJECTS是数据库的一个字典表,记录了你所登陆的用户和你有权限访问的其他用户的对象信息.
    你用SQLPLUS查一下就明白:
    SQL>SELECT * FROM all_objects WHERE owner=user;
      

  7.   

    二楼的解法比较简便,增加一个ORDER BY
    select T.姓名,T.month 月份,M.salary 工资 
    from 
    (select * 
    from (select rownum month from all_objects where rownum <=12)a, 
    (select distinct strName 姓名 from tbl_star_pay)b 
    )T 
    left join tbl_star_pay M 
    on T.姓名=M.strName and T.month=M.strMonth  order by T.month
      

  8.   

    select T.姓名,T.month 月份,nvl(M.工资,0)
    from
    (select *
    from (select rownum month from all_objects where rownum <=12)a,
    (select distinct 姓名 from 表)b
    )T
    left join 表 M
    on T.姓名=M.姓名 and T.month=M.月份