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

查询多个字段值,且要求所查询的结果中某一个字段的值都不相同
假如有一个表A
我想从中查找字段A1,A2,A3,A4
但是要求,字段A1的值不能有相同的记录,不知如何写Select语句。


------解决方案--------------------
select top 1 * from A where A1 in (select top 1 A1 from A )
union all
select * from A t where A1 not in (select top 1 A1 from A)
------解决方案--------------------
select A1,A2,A3,A4 from 表 as T
where id > (select min(id) from 表 where A1=T.A1)
------解决方案--------------------
当然办法是最苯的了
create table #t(a int,b int,c int)
insert into #t select 1,1,1
union all select 1,1,2
union all select 3,1,2
union all select 3,1,2
union all select 4,3,2
union all select 4,4,2
union all select 4,5,2
union all select 4,6,2

declare t_cursor cursor
for select a,b,c from #t order by a
declare @a int,@b int,@c int
declare @test table(a int,b int,c int)
open t_cursor
fetch next from t_cursor into @a,@b,@c
while @@fetch_status=0
begin
if not exists(select 1 from @test where a=@a)
insert into @test select @a,@b,@c
fetch next from t_cursor into @a,@b,@c
end
select * from @test
close t_cursor
deallocate t_cursor


drop table #t