34,591
社区成员
发帖
与我相关
我的任务
分享
--> 测试数据: #TA
if object_id('tempdb.dbo.#TA') is not null drop table #TA
GO
create table #TA (省份 varchar(4),城市 varchar(4),数 int,id int)
insert into #TA
select '江苏','南京',3,1 union all
select '江苏','南京',3,2 union all
select '江苏','南京',3,3
--> 测试数据: #TB
if object_id('tempdb.dbo.#TB') is not null drop table #TB
GO
create table #TB (省份 varchar(4),城市 varchar(4),数 int,id int)
insert into #TB
select '江苏','南京',2,4 union all
select '江苏','南京',2,5
;with cte as
(
select 省份,城市,id from #TA
UNION ALL
select 省份,城市,id from #TB
)
select *,n=(select sum(distinct 数) from #ta) +(select sum(distinct 数) from #tb)
from cte
省份 城市 id n
---- ---- ----------- -----------
江苏 南京 1 5
江苏 南京 2 5
江苏 南京 3 5
江苏 南京 4 5
江苏 南京 5 5
(5 行受影响)
--> 测试数据: #TA
if object_id('tempdb.dbo.#TA') is not null drop table #TA
GO
create table #TA (省份 varchar(4),城市 varchar(4),数 int,id int)
insert into #TA
select '江苏','南京',3,1 union all
select '江苏','南京',3,2 union all
select '江苏','南京',3,3
--> 测试数据: #TB
if object_id('tempdb.dbo.#TB') is not null drop table #TB
GO
create table #TB (省份 varchar(4),城市 varchar(4),数 int,id int)
insert into #TB
select '江苏','南京',2,4 union all
select '江苏','南京',2,5
;with cte as
(
select 省份,城市,id from #TA
UNION ALL
select 省份,城市,id from #TB
)
select *,n=(select count(*) from cte) from cte
省份 城市 id n
---- ---- ----------- -----------
江苏 南京 1 5
江苏 南京 2 5
江苏 南京 3 5
江苏 南京 4 5
江苏 南京 5 5
(5 行受影响)