日期:2014-05-19  浏览次数:20454 次

100分求两个多表联合查询的sql语句
1.两个表中都有a,b,c,d,根据Group   By   a,b,c,d,如何把两个表中的其他字段的和值连接起来写成一条记录,sql语句就类似下面的:
Select   Sum(a.x),Sum(a,xx),Sum(b.x),Sum(b,xx)   from   ……

2.这个跟第一个差不多,也是两个表的和值连接起来写成一个记录,只是比第一个复杂,在第一个表中计算的和值要减去某一和值
详细说明一下:
在第一个表中有一个字段来标示该记录是否包含某记录的数据(就是类似父记录和子记录的关系),当统计和值的记录同时包含子父记录和子记录时,计算和值的时候要把子记录剔除掉。如何写sql?   并不是所有的时候都同时包含父子记录,只有判断当父记录含有子记录时,才要把子记录去掉

不知道我说明白了没有,大家请帮帮忙


------解决方案--------------------
select * from
(
select a,b,c,d,sum(e) e
from table1
group by a,b,c,d
) t1
join
(
select a,b,c,d,sum(f) f
from table2
group by a,b,c,d
) t2
on t2.a = t1.a and t2.b=t1.b and t2.c = t1.c and t2.d = t1.d


------解决方案--------------------
select a,b,c,d, sum(case when 是子记录 then 0 else e end) e
from table1
group by a,b,c,d
------解决方案--------------------
1。两个表的外关联有4个键马?架设是的,语句如下:
select Sum(a.x) as ax,Sum(a,xx) as axx,Sum(b.x) as bx,Sum(b,xx) as bxx from a inner join b on a.a = b.a and a.b=b.b and a.c=b.c and a.d=b.d group by a.a,a.b,a.c,a.d

2. 参考语法:
select (CASE WHEN a.fatherValue is not NULL and b.childValue is not Null
THEN a.fatherValue ELSE b.childValue END) AS Value
from a inner join b on a.a = b.a
------解决方案--------------------
不大清楚,而且做了也未必是你想要的
------解决方案--------------------
呵呵,我来回答LZ第一个问题:
用存储过程吧:
declare global temporary table 临时表
(
a char(4),
b char(6),
c char(4),
d char(4),
ax integer,
bx integer,
axx decimal(12,2),
bxx integer
)not logged with replace;数据类型你自己调整啊,我是从我的代码COPY出来的

然后
insert into session.临时表
(
a,b,c,d,ax,bx,axx,bxx
)
select
a,b,c,d,Sum(ax), '0 ',Sum(axx), '0 '
from 第一个表dd
Group By a,b,c,d


同理在把第二个表cc放进来


然后把临时表一汇总就OK了,哈哈

------解决方案--------------------
不会
帮顶