日期:2014-05-18  浏览次数:20445 次

两张表中查询出不重复的记录,一条sql语句完成.谢谢大家
A.用户表

ID   用户名
1     a
2     b
3     c
4     d

B.用户订单表
ID   用户ID   订单内容
1     1               dfdfdf
2     1               dgfhfhf
3     1               gjhgmngb
4     4               ererer

我想从用户的订单表中查询出每个用户的一条订单内容.只需要一条.用一条sql语句怎么做呢....用Distinct的话.订单内容出不来.Distinct是对全部字段进行判断重复消除...但我又想输出订单内容.

------解决方案--------------------
declare @a table(ID int, 用户ID int, 订单内容 varchar(190))
insert @a select 1 ,1, 'dfdfdf '
union all select 2 ,1 , 'dgfhfhf '
union all select 3 ,1, 'gjhgmngb '
union all select 4 ,4, 'ererer '


select 用户id, 订单内容 from @a a where not exists(select 1 from @a where 用户id=a.用户id and len(订单内容)> len(a.订单内容))
------解决方案--------------------
select A.用户名,max(len(订单内容)) from A,B where A.ID=B.用户ID group by A.用户名--保留订单内容长的
select A.用户名,B.订单内容 from A,B where A.ID=B.用户ID group by A.用户名,B.订单内容--保留所有不重复的订单内容