34,576
社区成员
发帖
与我相关
我的任务
分享
select 表1.CBYF,sum(isnull(表1.ZSF,0))+sum(isnull(表2.ZSF,0))
from 表1 left join 表2 on 表1.CBYF=表2.CBYF
group by 表1.CBYF
SELECT CBYF , SUM(ZSF)ZSF FROM (
SELECT * FROM 表1
UNION ALL
SELECT * FROM 表2
)T GROUP BY CBYF
if object_id('table1') is not null
drop table table1
go
create table table1(CBYF varchar(6),ZSF varchar(10))
go
insert into table1 values ('200811','20')
insert into table1 (CBYF) values ('200912')
go
if object_id('table2') is not null
drop table table2
go
create table table2(CBYF varchar(6),ZSF varchar(10))
go
insert into table2 values ('200811','30')
insert into table2 values ('200912','40')
go
select CBYF,sum(cast(ZSF as int)) from (
select CBYF,ZSF=isnull(ZSF,0) from table1
union all
select CBYF,ZSF=isnull(ZSF,0) from table2
)a group by CBYF
--借樓上數據
---测试数据---
if object_id('[表1]') is not null drop table [表1]
go
create table [表1]([CBYF] int,[ZSF] int)
insert [表1]
select 200811,20 union all
select 200812,null
if object_id('[表2]') is not null drop table [表2]
go
create table [表2]([CBYF] int,[ZSF] int)
insert [表2]
select 200811,30 union all
select 200812,40
SELECT CBYF , SUM(ZSF)ZSF FROM (
SELECT * FROM 表1
UNION ALL
SELECT * FROM 表2
)T GROUP BY CBYF
/*CBYF ZSF
----------- -----------
200811 50
200812 40
(影響 2 個資料列)
警告: 彙總 (aggregate) 或其他 SET 操作已消除 Null 值。*/
---测试数据---
if object_id('[表1]') is not null drop table [表1]
go
create table [表1]([CBYF] int,[ZSF] int)
insert [表1]
select 200811,20 union all
select 200812,null
if object_id('[表2]') is not null drop table [表2]
go
create table [表2]([CBYF] int,[ZSF] int)
insert [表2]
select 200811,30 union all
select 200812,40
---查询---
select
a.CBYF,
sum(isnull(a.ZSF,0))+sum(isnull(b.ZSF,0)) as ZSF
from 表1 a,表2 b
where a.CBYF=b.CBYF
group by a.CBYF
---结果---
CBYF ZSF
----------- -----------
200811 50
200812 40
(所影响的行数为 2 行)
select
a.CBYF,
sum(a.ZSF)+sum(b.ZSF) as ZSF
from 表1 a,表2 b
SELECT CBYF , SUM(ZSF)ZSF FROM (
SELECT * FROM 表1
UNION ALL
SELECT * FROM 表2
)T GROUP BY CBYF