首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

三张表联合查询,并过滤重复数据的有关问题,请问【多谢】

2012-08-30 
三张表联合查询,并过滤重复数据的问题,请教【谢谢】a表字段:姓名,年龄,性别b表字段:姓名,住址,消费Bc表字段:

三张表联合查询,并过滤重复数据的问题,请教【谢谢】
a表字段:
姓名,年龄,性别
b表字段:
姓名,住址,消费B
c表字段:
姓名,电话,消费C

我要显示结果为
姓名,年龄,性别,消费B,消费C

a表中在b,c表中姓名相同的记录的消费b和消费c,如同个姓名在a,b,c表中存在多次,则过滤重复,任意取一个。
例:
a表字段:
姓名,年龄,性别
王二,18,男
王二,19,男
张三,18,男
b表字段:
姓名,住址,消费B
王二,18,电视
张三,19,电视
张三,20,冰箱
c表字段:
姓名,电话,消费C
王二,18,西瓜
王二,19,南瓜
张三,18,冰糕
张三,19,冰水

最后查询的结果应该为:
姓名,年龄,性别,消费B,消费C
王二,18, 男, 电视 西瓜
张三,18, 男, 电视 冰糕
-----------------------------------------
请问这样的sql语句怎么写啊?谢谢各位大哥了,我想了一天了

[解决办法]
直接inner join
[解决办法]
表设计成这个样子。。晕死 什么记录阿
[解决办法]
select *,id=identity(int,1,1) into # from a inner join b on a.姓名-b.姓名 inner join c on a.姓名=c.姓名
select * from # a where not exists (select 1 from # b where a.id<b.id)
[解决办法]

SQL code
-----------------------------------  Author: htl258(Tony)--  Date  : 2009-08-05 23:02:31-----------------------------------> 生成测试数据表:aIf not object_id('[a]') is null    Drop table [a]GoCreate table [a]([姓名] nvarchar(2),[年龄] int,[性别] nvarchar(1))Insert aSelect '王二',18,'男' union allSelect '王二',19,'男' union allSelect '张三',18,'男'Go--Select * from a--> 生成测试数据表:bIf not object_id('[b]') is null    Drop table [b]GoCreate table [b]([姓名] nvarchar(2),[住址] int,[消费B] nvarchar(2))Insert bSelect '王二',18,'电视' union allSelect '张三',19,'电视' union allSelect '张三',20,'冰箱'Go--Select * from b--> 生成测试数据表:cIf not object_id('[c]') is null    Drop table [c]GoCreate table [c]([姓名] nvarchar(2),[电话] int,[消费C] nvarchar(2))Insert cSelect '王二',18,'西瓜' union allSelect '王二',19,'南瓜' union allSelect '张三',18,'冰糕' union allSelect '张三',19,'冰水'Go--Select * from c-->SQL查询如下:select a.*,b.消费B,c.消费C from (select * from a t where not exists(select 1 from a where [姓名]=t.[姓名] and [年龄]<t.[年龄])) a  left join (select * from b t where not exists(select 1 from b where [姓名]=t.[姓名] and [住址]<t.[住址])) b    on a.姓名=b.姓名  left join (select * from c t where not exists(select 1 from c where [姓名]=t.[姓名] and [电话]<t.[电话])) c    on a.姓名=c.姓名/*姓名   年龄          性别   消费B  消费C---- ----------- ---- ---- ----王二   18          男    电视   西瓜张三   18          男    电视   冰糕(2 行受影响)*/
[解决办法]
SQL code
select distinct a.*,b.消费B,c.消费C from [a] , b ,cwhere a.姓名=b.姓名 and a.姓名=c.姓名and not exists(select 1 from a t where 姓名=a.姓名 and 年龄<a.年龄)and not exists(select 1 from b t where 姓名=b.姓名 and 住址<b.住址)and not exists(select 1 from c t where 姓名=c.姓名 and 电话<c.电话) 

热点排行
Bad Request.