SQL查询最大最小值的示例


  本文标签:SQL查询

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

  1. declare @Category table   
  2. (   
  3. id int identity(1,1) not null,   
  4. CategoryId int,   
  5. CategoryName varchar(50)   
  6. )   
  7. declare @MostExpensive table   
  8. (   
  9. ProductName varchar(50)   
  10. )   
  11. declare @counter int,@number int   
  12. set @counter=0   
  13. insert @Category select CategoryId,CategoryName from Categories   
  14. select @number=count(*) from @Category   
  15. while @counter<@number   
  16. begin   
  17. set @counter=@counter+1   
  18. insert @MostExpensive select top 3 ProductName from products where categoryid=(select CategoryId from @Category where id=@counter) order by UnitPrice desc   
  19. end   
  20. select * from @MostExpensive