使用SQL子查询实现查找唯一值


  本文标签:SQL子查询

  下文为您介绍的是使用SQL子查询,实现查找唯一值的目的,该方法供您参考学习,希望对您了解SQL子查询有些帮助  。

  实现原理为:先取不与我相同的标识号的内容,而我的内容又不存在这些内容中,所以我的内容是唯一的.即即唯一值

  SQL子查询例子:在一个用户表中取出唯一组的用户

  1. if object_id(Test_Users) is not null  
  2. drop table Test_Users  
  3. go  
  4.  
  5. create table Test_Users(AutoID int identity(1,1) primary key,UserGroupID int,UserName varchar(50))  
  6. go  
  7. set xact_abort on  
  8. begin tran  
  9. insert into Test_Users(UserGroupID,UserName)  
  10. select 2,aa union  
  11. select 2,bb union  
  12. select 3,cc union  
  13. select 1,Admin union  
  14. select 3,ff union  
  15. select 2,pp   
  16. commit tran  
  17. go  
  18.  
  19. select * from Test_Users a  
  20. where UserGroupID not in  
  21. (select UserGroupID from Test_Users where AutoID<>a.AutoID)  

  ---这样找出的结果是

  1. AutoID      UserGroupID UserName                                             
  2. ----------- ----------- --------------------------------------------------   
  3. 1           1           Admin  
  4.  
  5. (所影响的行数为 1 行)