問題|最大值 曾經看到一個文章,是問怎麼一次(用一條查詢語句)就查詢出一個表中的最大值和最小值,其中一位這樣回答的:(拿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