读书人

一个sql语句把小弟我难住了?distrinct

发布时间: 2012-01-15 22:57:48 作者: rapoo

一个sql语句把我难住了?distrinct
如有a,b,c,d四列,怎么得到只有a唯一的查询.
现状:
a b c d
1 2 5 6
1 2 8 10
2 3 4 7
2 0 4 9
希望的效果:
a b c d
1 2 5 6
2 3 4 7

即不管b,c,d重复,只取a不重复的第一行.

怎么写???

[解决办法]
select id=identity(int,1,1),* into # from 表
select * from # t where id=
(select top 1 id from # where a=t.a)
drop table #,表
[解决办法]
create table t
(a int, b int, c int, d int)
insert into t
select 1, 2, 5, 6 union all
select 1, 2, 8, 10 union all
select 2, 3, 4, 7 union all
select 2, 0, 4, 9


select identity(int,1,1)as id,* into #t from t


Select a,b,c,d From #t A
Where Exists (Select Count(*) From #t Where id <A.id and a = A.a Having Count(*) < 1)
Order By a


a b c d
----------- ----------- ----------- -----------
1 2 5 6
2 3 4 7

(2 row(s) affected)

读书人网 >SQL Server

热点推荐