求解惑:max函数问题
本帖最后由 athwind 于 2013-10-13 17:18:10 编辑 有一个表tb,主键为ID,自增长int类型,3条记录
ID
3
6
7
为了获取前2条记录的最大ID,于是很easy的写出了以下语句:
select max(ID) from (select top 2 ID from tb) t
------结果
7
很困惑,应该为6才对啊,因为select top 2 ID from tb的返回
3
6
测试发现select max(ID) from (select top N ID from tb) t始终返回当前表的最大值
只有在N=1时,即:
select max(ID) from (select top 1 ID from tb) t
或显式的加了order by之后才符合预期,即:
select max(ID) from (select top N ID from tb order by ID) t
求解惑
ps:数据库为Sql Server 2008
[解决办法]
create table tt(id int not null identity(1,1))
insert into tt
default values
insert into tt
default values
insert into tt
default values
insert into tt
default values
insert into tt
default values
insert into tt
default values
insert into tt
default values
select * from tt
delete from tt
where id not in (3,6,7)
select top 2 ID from tt
/*
ID
3
6
*/
select max(ID)
from (
select top 2 ID from tt
) t
/*
(无列名)
6
*/
-- 测试1, tb1.ID是主键
create table tb1
(ID int identity(1,1) not null
constraint pk_tb1 primary key(ID)
)
set identity_insert tb1 on
insert into tb1(ID)
select 3 union all
select 6 union all
select 7
set identity_insert tb1 off
select max(ID) 'maxID'
from (select top 2 ID from tb1) t
/*
maxID
-----------
7
(1 row(s) affected)
*/
-- 测试2, tb2.ID不是主键
create table tb2
(ID int identity(1,1) not null
)
set identity_insert tb2 on
insert into tb2(ID)
select 3 union all
select 6 union all
select 7
set identity_insert tb2 off
select max(ID) 'maxID'
from (select top 2 ID from tb2) t
/*
maxID
-----------
6
(1 row(s) affected)
*/
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-10-14 08:13:51
-- Version:
-- Microsoft SQL Server 2014 (CTP1) - 11.0.9120.5 (X64)
--Jun 10 2013 20:09:10
--Copyright (c) Microsoft Corporation
--Enterprise Evaluation Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([ID] int)
insert [tb]
select 3 union all
select 6 union all
select 7
--------------开始查询--------------------------
select max(ID) from (select top 2 ID from tb) t
----------------结果----------------------------
/*
-----------
6
*/