下面这个SQL查询最大最小值的例子使用了Northwind数据库,取出每种书目中价格最贵的3本书,希望可以让您对SQL查询有更多的认识。
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