- 爱易网页
-
MSSQL教程
- 4 表联合查询求和有关问题,求 SQL
日期:2014-05-19 浏览次数:20612 次
4 表联合查询求和问题,求 SQL !
表a:
ID CODE REQUEST
1 A001 代理
2 B003 自营
表b:
CODE CNAME
A001 王刚
B003 张翼
表c:
ID DETAIL INVOICE
1 材料费 500
1 人工费 40
1 加班费 50
1 误工费 80
1 加急费 100
1 交通费 30
1 午餐费 10
1 晚餐费 12
。。
表d:
ID ACCOUNTNAME ACCOUNT
1 服务费 800
1 误工费 80
1 加急费 100
1 加班费 50
1 交通费 30
1 餐费 30
想根据CNAME查询,得到如下结果:
CNAME ID CODE REQUEST 应收 成本 毛利
王刚 1 A001 代理 860 592 268
应收要排除加班费、误工费、加急费,成本同样要排除加班费、误工费、加急费
------解决方案--------------------
select b.cname,
a.id,
a.code,
a.requset,
c1.cnt as 应收,
d1.cnt as 成本,
(c1.cnt - d1.cnt) as 毛利
from a,
b,
(select id, sum(INVOICE) cnt
from (select id, detail, INVOICE
from c
where detail <> '加班费 ' and detail <> '误工费 ' and
detail <> '加急费 ')
group by id) c1,
(select id, sum(ACCOUNT) cnt
from (select id, ACCOUNTNAME, ACCOUNT
from d
where ACCOUNTNAME <> '加班费 ' and ACCOUNTNAME <> '误工费 ' and
ACCOUNTNAME <> '加急费 ')
group by id) d1
where a.code = b.code and a.id = c1.id and a.id = d1.id and
b.cname = '王刚 '
------解决方案--------------------
select B.CName,A.ID,A.Code,A.REQUEST,(select sum(加减各字段) from C where ID=A.ID),(select sum (加减各字段) from D where ID=A.ID),(select sum(加减各字段) from C where ID=A.ID)- (select sum (加减各字段) from D where ID=A.ID),( from A inner join B on A.CODE=B.Code where CName= '王刚 '