--@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,7select * 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
*/
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,7select * 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
*/
解决方案 »
- 指定某个软件能访问SQL,如何实现
- SQL 0带头的纯数字怎么储存
- 同一个数据库中表结构的复制
- 一个join 查询sql在sql server中执行没有错误,而在access数据库中执行却错误,大家来看看
- 求一计算行数的语句(条件如下)
- 各位帮帮忙,急,求一个sql语句~~~~~~~~~~~~!
- SQLSwever设置主键时不能保存,各位大神帮忙
- 怎样用Ms SQL Sverver Management Studio Express把远程数据库备份到本地硬盘上?
- 求问下两条语句的问题在哪?
- 请大伙帮忙看看吧,急!
- 我碰到最不可理解的问题,哪个大虾帮忙解惑?高分求救
- 按顺序按时间提取数据库记录的操作
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())
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,7select * 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 行受影响)
但我想,能不能不用临时表,直接用一条select语句,得到结果?
不知道你有没有发现,在查询的表中必须有一列值是无重复的,要不能,就得不错结果!就如下表所示,
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
-----------------------------------------------------------------
还是一样产生了重复值