当前位置: 代码迷 >> Sql Server >> 求一复杂又简单的Sql文, 请大家多指教,该如何处理
  详细解决方案

求一复杂又简单的Sql文, 请大家多指教,该如何处理

热度:37   发布时间:2016-04-27 16:31:31.0
求一复杂又简单的Sql文, 请大家多指教
有一表   Id   Name  
              1     cj1  
              1     cj  
              1     cj2  
              2     gp
              3     zs  

我要查询所以的记录,但是如果记录中Id字段的值相等,则取Id字段值相等的第一条记录。(注意:Id不是主键,如果Id值相同,取第一条记录)  

比如   想获得的查询结果为  
          Id   Name
          1     cj1  
          2     gp
          3     zs  

我有一个Sql文   select   Id,Min(Name)   from   table1   group   by   Id   ,它能获得不同Id的记录值。但不能保证,如果Id字段值相等,取相等的第一条记录。  

请大家多指教!

------解决方案--------------------
create table t(Id int,Name varchar(10))
insert t select 1, 'cj1 '
union all select 1, 'cj '
union all select 1, 'cj2 '
union all select 2, 'gp '
union all select 3, 'zs '

select Id,Name from t a
where Name = ( select top 1 Name from t b where b.Id = a.Id)

drop table t

Id Name
----------- ----------
1 cj1
2 gp
3 zs
  相关解决方案