A表内容
客户编码 客户名称 2006年发货额
01 A 20
02 B 30
04 D 60B表内容
客户编码 客户名称 2007年发货额
02 B 50
03 C 10
04 D 100想查询结果为这样
客户编码 客户名称 2006年发货额 2007年发货额 增长额
01 A 20 0 -20
02 B 30 50 20
03 C 0 10 10
04 D 60 100 40
合计 110 160 50sql语句怎样写?
客户编码 客户名称 2006年发货额
01 A 20
02 B 30
04 D 60B表内容
客户编码 客户名称 2007年发货额
02 B 50
03 C 10
04 D 100想查询结果为这样
客户编码 客户名称 2006年发货额 2007年发货额 增长额
01 A 20 0 -20
02 B 30 50 20
03 C 0 10 10
04 D 60 100 40
合计 110 160 50sql语句怎样写?
from
(
select distinct 客户编码 客户名称 from 表A
union
select distinct 客户编码 客户名称 from 表B
)
该视图用v表示
----------------------------select 客户编码 客户名称,isnull(A.2006年发货额,0) as 2006年发货额
,isnull(B.2007年发货额,0) as 2007年发货额
,(isnull(A.2006年发货额,0)-isnull(B.2007年发货额,0)) as 增长额from v
LEFT OUTER JOIN A
on A.客户编码 = v.客户编码
LEFT OUTER JOIN B
on B.客户编码 = v.客户编码
bh varchar(10),
mc varchar(10),
je int)create table #2 (
bh varchar(10),
mc varchar(10),
je int)
insert #1
select '01', 'A', 20
union all
select '02', 'B', 30
union all
select '04', 'D', 60insert #2
select '02', 'B', 50
union all
select '03', 'C', 10
union all
select '04', 'D', 100select bh,mc,'06'=isnull((select sum(je) from #1 where #1.bh=B.bh),0),
'07'=isnull((select sum(je) from #2 where #2.bh=B.bh),0) ,
'z'=isnull((select sum(je) from #2 where #2.bh=B.bh),0)-isnull((select sum(je) from #1 where #1.bh=B.bh),0)
from
(
select distinct bh,mc from #1
union all
select distinct bh,mc from #2
) B
group by bh,mc
union all
select bh='合计',mc='','06'=(select sum(je) from #1),'07'=(select sum(je) from #2),
'z'=((select sum(je) from #1) - (select sum(je) from #2))
drop table #1
drop table #2
---------------------------------------------
结果
01 A 20 0 -20
02 B 30 50 20
03 C 0 10 10
04 D 60 100 40
合计 110 160 -50
select (case when A.客户编码 is not null then A.客户编码 else B.客户编码 end) as [客户编码]
,(case when A.客户编码 is not null then A.客户名称 else B.客户名称 end) as [客户名称]
,isnull(A.2006年发货额,0) as [2006年发货额]
,isnull(B.2007年发货额,0) as [2007年发货额]
,(isnull(2007年发货额,0) - isnull(2006年发货额,0)) as [增长额]
from A full join B on A.[客户编码] = B.[客户编码]
union all
select null,null
,sum(isnull(A.2006年发货额,0))
,sum(isnull(B.2007年发货额,0))
,sum(isnull(B.2007年发货额,0))-sum(isnull(A.2006年发货额,0))
from A full join B on A.[客户编码] = B.[客户编码]
group by A.[客户编码],B.[客户编码]