实例应用
if(object_id('a')is not null) drop table a
go
create table a
(
LX INT,
MMMC VARCHAR(3),
FS VARCHAR(1),
JHJE DECIMAL(18,2)
)
GO
INSERT INTO A
SELECT 1,'XM1','A',1000.00 UNION ALL
SELECT 1,'XM1','B',500.00 UNION ALL
SELECT 1,'XM2','A',600.00 UNION ALL
SELECT 1,'XM3','A',800.00 UNION ALL
SELECT 1,'XM4','A',700.00
GO
IF(OBJECT_ID('B')IS NOT NULL) DROP TABLE B
GO
create table B
(
LX INT,
MMMC VARCHAR(3),
FS VARCHAR(1),
ZXJE DECIMAL(18,2)
)
GO
INSERT INTO B
SELECT 1,'XM1','A',500.00 UNION ALL
SELECT 1,'XM1','B',200.00 UNION ALL
SELECT 1,'XM2','A',300.00 UNION ALL
SELECT 1,'XM3','A',400.00
go
select a.lx,a.mmmc,a.fs,case when b.zxje is not null then b.zxje else a.jhje end as JYJE
from a left outer join b on a.MMMC=b.MMMC and a.fs = b.fs
/*
lx mmmc fs JYJE
----------- ---- ---- ---------------------------------------
1 XM1 A 500.00
1 XM1 B 200.00
1 XM2 A 300.00
1 XM3 A 400.00
1 XM4 A 700.00
(5 行受影响)
*/
select a.lx,a.mmmc,a.fs,a.jhje-isnull(b.zxje,0) as jyje
from a
left join(
select lx,mmmc,fs,sum(zxje) as zxje from b group by lx,mmmc,fs
) b
on a.lx=b.lx and a.mmmc=b.mmmc and a.fs=b.fs
/**
lx mmmc fs jyje
----------- ---- ---- ---------------------------------------
1 XM1 A 500.00
1 XM1 B 300.00
1 XM2 A 300.00
1 XM3 A 400.00
1 XM4 A 700.00
(5 行受影响)
**/
with tb1(LX,MMMC,FS,JHJE)
as(
SELECT 1,'XM1','A',1000.00 UNION ALL
SELECT 1,'XM1','B',500.00 UNION ALL
SELECT 1,'XM2','A',600.00 UNION ALL
SELECT 1,'XM3','A',800.00 UNION ALL
SELECT 1,'XM4','A',700.00),
tb2(LX,MMMC,FS,ZXJE)
as(
SELECT 1,'XM1','A',500.00 UNION ALL
SELECT 1,'XM1','B',200.00 UNION ALL
SELECT 1,'XM2','A',300.00 UNION ALL
SELECT 1,'XM3','A',400.00)
select tb11.lx,tb11.mmmc,tb11.fs, tb11.jhje-isnull(
(select tb2.zxje from tb2 where tb2.lx=tb11.lx and tb2.mmmc=tb11.mmmc and tb2.fs=tb11.fs),0)
jhje from tb1 tb11