最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
关于查询出表中最大值和最小值的问题
时间:2022-06-30 10:32:06 编辑:袖梨 来源:一聚教程网
曾经看到一个帖子,是问怎么一次(用一条查询语句)就查询出一个表中的最大值和最小值,其中一位这样回答的:(拿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
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
相关文章
- Binance.US已上线VIRTUAL 04-30
- binance官网电脑下载_binance苹果版下载地址V2.57.7 04-30
- 比特币交易量最大的交易所是哪个?全球最大的比特币交易平台排名 04-30
- 奥比岛梦想国度卡死闪退有哪些解决方法 04-30
- DNF手游骨戒在哪个位置 04-30
- 回望羊驼:当利空成为短暂的财富密码 04-30