表1的字段和记录:
a1 b1 c1 d1 e1 f1
张三 男 长沙 汉族 25 大专
李四 女 广州 汉族 20 大专
表2的字段和记录
a2 b2 c2 d2 e2 g1
王五 女 株州 回族 27 1980-1-3
要求按条件查得的记录集:
A b C D E
张三 男 长沙 汉族 25
李四 女 广州 汉族 20
王五 女 株州 回族 19而且需要引用其中的字段进行统计,如统计多少男性,多少汉族等.
谢谢
a1 b1 c1 d1 e1 f1
张三 男 长沙 汉族 25 大专
李四 女 广州 汉族 20 大专
表2的字段和记录
a2 b2 c2 d2 e2 g1
王五 女 株州 回族 27 1980-1-3
要求按条件查得的记录集:
A b C D E
张三 男 长沙 汉族 25
李四 女 广州 汉族 20
王五 女 株州 回族 19而且需要引用其中的字段进行统计,如统计多少男性,多少汉族等.
谢谢
union all
select a2,b2,c2,d2,e2 from table2select count(*) from
(
select a1 as A ,b1 as B,c1 as C,d1 as D,e1 as E from table1
union all
select a2,b2,c2,d2,e2 from table2
) t where t.B='男' ...
where 就自己根据条件写了撒
union all
select a2,b2,c2,d2,e2 from table2select count(*) from
(
select a1 as A ,b1 as B,c1 as C,d1 as D,e1 as E from table1
union all
select a2,b2,c2,d2,e2 from table2
) t where t.B='男' ...
where 就自己根据条件写了撒
a1 b1 c1 d1 e1 f1
张三 男 长沙 汉族 25 大专
李四 女 广州 汉族 20 大专
表2的字段和记录
a2 b2 c2 d2 e2 g1
王五 女 株州 回族 27 1980-1-3
要求按条件查得的记录集:
A b C D E
张三 男 长沙 汉族 25
李四 女 广州 汉族 20
王五 女 株州 回族 19
------------
那个19怎么来的?
union all
连接
注意,表列的数量必须相同,顺序也要一至
表2多了一个g1去掉
select sum(case B when '男' then 1 else 0 end) as '男性数量',
count(distinct D) as '汉族数量'
from
(select [A]=a1 ,[B]=b1 ,[C]=c1,[D]=d1,[E]=e1 from t1
union all
select a2,b2,c2,d2,e2 from t2 )temp
select b1,count(*) 数量from
(
select a1,b1,c1,d1,e1 from 表1
union all
select a2,b2,c2,d2,e2 from 表2
) t
group by b1
--民族
select d1,count(*) 数量from
(
select a1,b1,c1,d1,e1 from 表1
union all
select a2,b2,c2,d2,e2 from 表2
) t
group by d1
insert @t select '张三','男','长沙','汉族','25','大专'
insert @t select '李四','女','广州','汉族','20','大专 'declare @tt table(a2 varchar(10),b2 varchar(10),c2 varchar(10),d2 varchar(10),e2 varchar(10),g3 varchar(10))
insert @tt select '王五','女','株州','回族','27 ','1980-1-3 '
select sum(case D when '汉族' then 1 else 0 end) as '汉族人数',
sum(case B when '女' then 1 else 0 end ) as '女性人数'
from
(select A=a1 ,B=b1 ,C=c1,D=d1,E=e1 from @t
union all
select a2,b2,c2,d2,e2 from @tt ) ttt
啊哈啊哈,潇洒老乌龟写的都试过了,可以得出LZ想要的结果
表1和表2,分别在不同的两个SQL服务器的库里面,源不同,怎么能执行这个查询?
'SQLOLEDB',
'服务器';'用户名';'密码',数据库.dbo.table1
) tunion all select a2,b2,c2,d2,e2 from OPENROWSET(
'SQLOLEDB',
'服务器';'用户名';'密码',数据库.dbo.table2
) t1
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO