读书人

一个多表查询

发布时间: 2012-10-10 13:58:11 作者: rapoo

求助一个多表查询
A表
库存金额 经办人
500 小刘
400 小刘
300 小张
……

B表
销售金额 经办人
50 小刘
40 小刘
30 小张
……

要按经办人分类分析出的表下面的表应该怎么写sql查询代码呢?

经办人库存金额销售金额
小刘 900 90
小张 300 30
……


[解决办法]

SQL code
select a.经办人,sum(a.库存金额)库存金额,sum(b.销售金额)销售金额 from A表 a, B表 bwhere a.经办人 = b.经办人 and a.id=b.id/*注:两个表之间应该还有别的相连的关系,让A表的500对应B表的50而你没有列出来,如果实在没有,就需要给他们编号,对应编号相连*/
[解决办法]

select case when a.经办人 IS null then b.经办人 else a.经办人 end as 经办人,a.库存金额 ,b.销售金额 from
(
select 经办人, SUM(库存金额) as 库存金额 from a group by 经办人
) a
full out join
(
select 经办人, SUM(销售金额) as 销售金额 from b group by 经办人
)b
on a.经办人=b.经办人
[解决办法]
SQL code
create table ta(库存金额 float, 经办人 nvarchar(20), )  create table tb(销售金额 float, 经办人 nvarchar(20), )insert taselect 500, '小刘'    union allselect 400,'小刘'union all    select 300,'小张'insert into tbselect 50, '小刘'    union allselect 40,'小刘'union all    select 30,'小张'select case a.经办人 when null then b.经办人 else a.经办人 end as 经办人,a.库存金额, b.销售金额from    (        select SUM (库存金额) 库存金额 ,经办人  from ta            group by 经办人        ) a full join         (        select SUM (销售金额) 销售金额 ,经办人  from tb            group by 经办人        ) b on a.经办人=b.经办人drop table tadrop table tb
[解决办法]
SQL code
select a.经办人,sum(a.库存金额) as '库存金额',sum(b.销售金额) as '销售金额' from a inner join b on a.经办人=b.经办人group by a.经办人
[解决办法]
SQL code
select a.经办人,sum(a.库存金额)as 库存金额,sum(b.销售金额)as 销售金额 from A表 a, B表 bwhere a.经办人 = b.经办人 group by a.经办人
[解决办法]
SQL code
select a.经办人,       sum(a.库存金额),       sum(b.销售金额)from a left join b on a.经办人=b.经办人group by a.经办人 

读书人网 >SQL Server

热点推荐