一个复杂变态的查询问题!

迷失2046 2007-09-19 12:18:15
假如我有一张表,表名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
...全文
143 11 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
Limpire 2007-09-19
  • 打赏
  • 举报
回复
--@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())
Limpire 2007-09-19
  • 打赏
  • 举报
回复
--@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
*/
迷失2046 2007-09-19
  • 打赏
  • 举报
回复
还有个问题呀,如果按照你那写法,
不知道你有没有发现,在查询的表中必须有一列值是无重复的,要不能,就得不错结果!就如下表所示,
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
-----------------------------------------------------------------
还是一样产生了重复值

迷失2046 2007-09-19
  • 打赏
  • 举报
回复
谢谢了,小楼
ojuju10 2007-09-19
  • 打赏
  • 举报
回复
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

(3 行受影响)

free1879 2007-09-19
  • 打赏
  • 举报
回复
这个昨夜小楼和老乌龟太快了
giftzheng 2007-09-19
  • 打赏
  • 举报
回复
答案都答出花了
zs621 2007-09-19
  • 打赏
  • 举报
回复
select * from test a where c1=(select top 1 c1 from test where type=a.type)
迷失2046 2007-09-19
  • 打赏
  • 举报
回复
谢谢啦!
但我想,能不能不用临时表,直接用一条select语句,得到结果?
anison 2007-09-19
  • 打赏
  • 举报
回复
~~~都说对了~
bluebullet 2007-09-19
  • 打赏
  • 举报
回复
我说昨夜小楼和老乌龟,
生活在用一片天空下,
你们咋就那么强呢?
咋就那么强呢?
那么强呢?
强呢?

22,300

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧