表1:
工号   姓名
11      aaa
22      bbb
表2:
工号    金额     时间
11      12.01  2004-1
11      13     2004-1
22      55     2004-3
22      78     2004-1
实现的功能是:
工号  姓名    发生金额   
            1月    2月    3月  4月。
11    aaa   25.01   0     0    0。
22    bbb   78      0     55    0。 
最好用一句sql语句,谢谢了

解决方案 »

  1.   

    SELECT 表1.ID,M1.AMT,M2.AMT,……M12.AMT
    FROM 表1
    LEFT JOIN (SELECT 1月的金额,按工号分组 FROM 表2) M1
    LEFT JOIN (SELECT 2月的金额,按工号分组 FROM 表2) M2
    ……
    LEFT JOIN (SELECT 12月的金额,按工号分组 FROM 表2) M12
    WHERE ……
      

  2.   

    select b.工号,a.姓名,
      (select sum(金额) from 表2 where 工号=b.工号 and 时间>='2004-01-01' and 时间<='2004-01-31') as 1月,
    ...
    ...
    ...
    from 表1 a,表2 b
    where a.工号=b.工号不知道是否正确,我的思路就是这样的。
    是不是可以考虑更改一下数据结构,改得好的话可以使得代码写起来更容易一些。
      

  3.   

    str1='a.工号,a.姓名';
    str2='(select * from 表1) a'
    for i=1 to 12 do 
    begin
      str1:=str1+',i.发生金额';
      str2:=str2+',(select * from 表2 where substr(年月,6,1)=i) i';
    end
    str='select '+str1+' from '+str2
    with query do 
    begin
      close;
      sql.clear;
      sql.add(str)
      open;
    end  语法大概是这样的,你慢慢调试一下,前段时间我们做个项目中有这样的表,我就是这么做的
      

  4.   

    完整实现:select a.id,a.name ,M1.amt,M2.amt from tab_employee a
    left Join
    (select id,sum(amount) amt from tab_salary where period='2004-1' group by id  ) M1
    on a.id=m1.id
    left Join
    (select id,sum(amount) amt from tab_salary where period='2004-2' group by id  ) M2
    on a.id=m2.id
      

  5.   

    piyoufei(探索者)
    你这个语句执行不了
      

  6.   

    翻译一下,就是这样:
    select a.工号,a.姓名 ,M1.amt,M2.amt from 表1 a
    left Join
    (select 工号,sum(金额) amt from 表2 where 时间='2004-1' group by 工号  ) M1
    on a.工号=m1.工号
    left Join
    (select 工号,sum(金额) amt from 表2 where 时间='2004-2' group by 工号  ) M2
    on a.工号=m1.工号
      

  7.   

    强啊发现自己只能写出最简单的SQL语句 弱啊
      

  8.   

    http://community.csdn.net/Expert/topic/3267/3267704.xml?temp=.1666223你可以到数据库的oracle板块搜索一下decode函数的用法,会对你又帮助的
      

  9.   

    jinjazz(人雅的标记--落寞刺客), 你看他楼上的表现,别指望他会自己看帮助了,呵呵