表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语句,谢谢了
工号 姓名
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语句,谢谢了
FROM 表1
LEFT JOIN (SELECT 1月的金额,按工号分组 FROM 表2) M1
LEFT JOIN (SELECT 2月的金额,按工号分组 FROM 表2) M2
……
LEFT JOIN (SELECT 12月的金额,按工号分组 FROM 表2) M12
WHERE ……
(select sum(金额) from 表2 where 工号=b.工号 and 时间>='2004-01-01' and 时间<='2004-01-31') as 1月,
...
...
...
from 表1 a,表2 b
where a.工号=b.工号不知道是否正确,我的思路就是这样的。
是不是可以考虑更改一下数据结构,改得好的话可以使得代码写起来更容易一些。
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 语法大概是这样的,你慢慢调试一下,前段时间我们做个项目中有这样的表,我就是这么做的
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
你这个语句执行不了
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.工号