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

一道SQL查询语句
一个表有id和name两个字段,id是自增长整型主键,name是有可能重复的字符串字段,现在要取出id和name两列,且name不许重复,name如果有重复的数据,取id最小的name.

------解决方案--------------------

select * from table1 as t1 
where (not exists (select 1 as arp from table1 
where (id < t1.id) and (uname=t1.uname)))
------解决方案--------------------
select min(id) id , name from tb group by name
------解决方案--------------------
SQL code

--定义一个游标
DECLARE MY_CURSOR CURSOR
    FOR SELECT ID, NAME FROM [TABLE] ORDER BY NAME

--临时变量
DECLARE @ID INT, @NAME CHAR(20)
DECLARE @NAME_1 CHAR(20)
SET @NAME_1 = '999999';  --与数据库中的任一name都不相等


--创建临时表
CREATE 192.1

------解决方案--------------------
--仅仅两个字段,用上面即可.
--如果有多个字段.
--方法一:
select a.* from tb a,
(select min(id) id , name from tb group by name) b
where a.name = b.name and a.id = b.id
--方法二:
select a.* from tb a where id in (select min(id) from tb group by name)
------解决方案--------------------

一个表有id和name两个字段,id是自增长整型主键,name是有可能重复的字符串字段,
现在要取出id和name两列,且name不许重复,name如果有重复的数据,取id最小的name.
--------------------------------------
---方法1
Select Min(id) As id,Name From 表名 Group By Name
---方法2
Select * From 表名 As T Where Not Exists
(Select 1 From 表名 Where Name=T.Name And ID<T.ID)
---方法3
Select * From 表名 As T Where ID In (Select Min(ID) From 表名 Where Name=T.Name)

---方法4
Select * From 表名 As T Where ID In (Select Top 1 ID From 表名 Where Name=T.Name Order By ID)

---方法5
Select * From 表名 As T Where (Select Count(1) From 表名 Where Name=T.Name And ID<T.ID)<1

---方法6
Select * From 表名 As T Where Not Exists
(Select 1 From 表名 Where Name=T.Name And ID<T.ID Group By Name Having Count(1)>0)
------解决方案--------------------
select id=min(id), [name] from tb group by [name]
------解决方案--------------------
declare @table table(id int,name char(10))
insert into @table
select 1,'a' 
union all select 2,'a' 
union all select 3,'b' 
union all select 4,'c' 
union all select 5,'a' 
union all select 6,'b' 
union all select 7,'c' 

select min(id)as id,name from @table group by name

/*结果
id name
----------- ----------
1 a
3 b
4 c
*/

--------
难道这不是你想要的结果吗?
------解决方案--------------------
--按name分组,取最小的id
select 
min(id)as id,
name 
from 表名 
group by name