日期:2014-05-18 浏览次数:20589 次
--------------------------------- -- Author: htl258(Tony) -- Date : 2009-08-05 23:02:31 --------------------------------- --> 生成测试数据表:a If not object_id('[a]') is null Drop table [a] Go Create table [a]([姓名] nvarchar(2),[年龄] int,[性别] nvarchar(1)) Insert a Select '王二',18,'男' union all Select '王二',19,'男' union all Select '张三',18,'男' Go --Select * from a --> 生成测试数据表:b If not object_id('[b]') is null Drop table [b] Go Create table [b]([姓名] nvarchar(2),[住址] int,[消费B] nvarchar(2)) Insert b Select '王二',18,'电视' union all Select '张三',19,'电视' union all Select '张三',20,'冰箱' Go --Select * from b --> 生成测试数据表:c If not object_id('[c]') is null Drop table [c] Go Create table [c]([姓名] nvarchar(2),[电话] int,[消费C] nvarchar(2)) Insert c Select '王二',18,'西瓜' union all Select '王二',19,'南瓜' union all Select '张三',18,'冰糕' union all Select '张三',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 行受影响) */
------解决方案--------------------
select distinct a.*,b.消费B,c.消费C from [a] , b ,c where 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.电话)