假如我有一张表,表名test,有3个字段c1,c2,type
数据如下
c1 c2 type
第1行 a 9 5
第2行 b 8 5
第3行 c 7 6
第4行 d 6 6
第5行 e 5 7
现在我要写个查询语句,类型相同的数据,只要显示一行就可以了,
也就是上面的数据只要显示第1行,第3行,第5行!如下:
c1 c2 type
a 9 5
c 7 6
e 5 7
这查询语句该怎么写?
想了很久想不明白,郁闷ing
...全文
14111打赏收藏
一个复杂变态的查询问题!
假如我有一张表,表名test,有3个字段c1,c2,type 数据如下 c1 c2 type 第1行 a 9 5 第2行 b 8 5 第3行 c 7 6 第4行 d 6 6 第5行 e 5 7 现在我要写个查询语句,类型相同的数据,只要显示一行就可以了, 也就是上面的数据只要显示第1行,第3行,第5行!如下: c1 c2 type a 9 5 c 7 6 e 5 7 这查询语句该怎么写? 想了很久想不明白,郁闷ing
--@Test
declare @test table(c1 varchar(1),c2 int,type int)
insert @test
select 'a',9,5 union all
select 'b',8,5 union all
select 'c',7,6 union all
select 'd',6,6 union all
select 'e',5,7
--按记录顺序取第一条
select * from @test a where c1=(select top 1 c1 from @Test where type=a.type)
--取最小
select * from @test a where c1=(select min(c1) from @Test where type=a.type)
--取最大
select * from @test a where c1=(select max(c1) from @Test where type=a.type)
--随机取
select * from @test a where c1=(select top 1 c1 from @Test where type=a.type order by newid())
--@Test
declare @test table(c1 varchar(1),c2 int,type int)
insert @test
select 'a',9,5 union all
select 'b',8,5 union all
select 'c',7,6 union all
select 'd',6,6 union all
select 'e',5,7
select * from @test a where c1=(select top 1 c1 from @Test where type=a.type)
/*
c1 c2 type
a 9 5
c 7 6
e 5 7
*/
还有个问题呀,如果按照你那写法,
不知道你有没有发现,在查询的表中必须有一列值是无重复的,要不能,就得不错结果!就如下表所示,
c1 c2 type
第1行 a 9 5
第2行 a 1 5
第3行 b 9 5
第4行 b 8 5
第5行 c 7 6
第6行 d 6 6
第7行 e 5 7
第8行 e 5 7
就得不到想要的结果了!
select * from test a where c1=(select top 1 c1 from test where type=a.type)
查处的结果是,第1行,第2行,第5行,第7行
c1 c2 type
----------------------------------------------
第1行 a 9 5
第2行 a 1 5
第5行 c 7 6
第7行 e 5 7
第8行 e 5 7
-----------------------------------------------------------------
还是一样产生了重复值
declare @test table(c1 varchar(1),c2 int,type int)
insert @test
select 'a',9,5 union all
select 'b',8,5 union all
select 'c',7,6 union all
select 'd',6,6 union all
select 'e',5,7
select * from @test a
where not exists(select 1 from @test where a.type=type and a.c1>c1)
c1 c2 type
---- ----------- -----------
a 9 5
c 7 6
e 5 7