欢迎光临
我们一直在努力

关于查询出表中最大值和最小值的问题-ASP教程,数据库相关

建站超值云服务器,限时71元/月

曾经看到一个帖子,是问怎么一次(用一条查询语句)就查询出一个表中的最大值和最小值,其中一位这样回答的:(拿northwind的products表为例)

select top 1 * from products order by unitprice

union

select top 1 * from products order by unitprice desc

上面这个似乎正确,可是其实在使用了union的时候只有最后一条select命令才能使用order by参数,因此上面这样是不行的,在查询分析器中运行会爆出错误

下面提供查询出最大值和最小值的方法:

declare @highlow table

(

productname varchar(50)

)

insert @highlow select top 1 productname from products order by unitprice desc

insert @highlow select top 1 productname from products order by unitprice

select productname from @highlow

这种方法不是一次就查询出最大值和最小值,而是使用了一个table变量,将查询出的最大值和最小值保存入这个表中。

下面这个例子使用了northwind数据库,取出每种书目中价格最贵的3本书:

declare @category table

(

id int identity(1,1) not null,

categoryid int,

categoryname varchar(50)

)

declare @mostexpensive table

(

productname varchar(50)

)

declare @counter int,@number int

set @counter=0

insert @category select categoryid,categoryname from categories

select @number=count(*) from @category

while @counter<@number

begin

set @counter=@counter+1

insert @mostexpensive select top 3 productname from products where categoryid=(select categoryid from @category where id=@counter) order by unitprice desc

end

select * from @mostexpensive

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 关于查询出表中最大值和最小值的问题-ASP教程,数据库相关
分享到: 更多 (0)

相关推荐

  • 暂无文章