Questions about the maximum and minimum values in the query out table

Source: Internet
Author: User
Problem | Max once saw a post, is asked how once (with a query statement) on the query out of a table of the maximum and minimum values, one of these answers: (Take the Northwind Products table for example)
Select top 1 * from the products order by UnitPrice
Union
Select top 1 * from the products UnitPrice DESC
This seems to be the correct one, but in fact, when you use the Union, only the last select command can use the order by parameter, so this is not the case, running in Query Analyzer will burst the error

The following methods provide the maximum and minimum values for the query:
DECLARE @HighLow table
(
ProductName varchar (50)
)
Insert @HighLow Select top 1 Productname from the ORDER by UnitPrice DESC
Insert @HighLow Select top 1 Productname from [ORDER by UnitPrice
Select ProductName from @HighLow
Instead of querying the maximum and minimum values at once, this method uses a table variable to save the maximum and minimum values of the query into the table.


The following example uses the Northwind database to take out the 3 most expensive books in each bibliography:
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



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.