1

Here's my scenario... Multiple Items with multiple item types which have multiple prices. Want to select Items with all types showing the MAX price. Can't figure out how to get the max?

Input:

ProductId   ProductType Description     Price

1 A BAKED BEANS 1.29

1 B BAKED BEANS 1.98

Output:

ProductId   ProductType Description     Price

1 A BAKED BEANS 1.98

1 B BAKED BEANS 1.98

Any suggestions?

4 Answers 4

4

Try this:

SELECT ProductId, 
    ProductType,
    Description,
    b.price
  FROM <YOUR_TABLE> a, 
        (SELECT MAX(price) price FROM <YOUR_TABLE>) b

For those who love ANSI syntax:

SELECT ProductId, 
    ProductType,
    Description,
    b.price
  FROM <YOUR_TABLE> a INNER JOIN 
    (SELECT MAX(price) price FROM <YOUR_TABLE>) b
   ON 1=1
Sign up to request clarification or add additional context in comments.

2 Comments

Although, I would never recommend using the comma-separated syntax. The day will come when SQL Server will stop supporting it (if only it could happen sooner).
@Thomas: Updated the post with ANSII version of join
3
Select ProductId, ProductType, Description, MaxByDesc.MaxPrice
From Product
    Join    (
            Select Description, Max(Price) As MaxPrice
            From Product 
            Group By Description
            ) As MaxByDesc
        On MaxByDesc.Description = Product.Description

If you are using SQL Server 2005 or later:

Select ProductId, ProductType, Description
    , Max( Price ) Over ( Partition By Description ) As MaxPrice
From Product

1 Comment

It works. Thanks so much! I am using ROW_NUMBER() in my subquery to grab newest Price. Didn't know that I could use MAX() with Partition BY...
1

Thomas, right, except for that you need to group by type:

Select ProductId, ProductType, Description, MaxByDesc.MaxPrice
From Product
Join    (
        Select Description, Max(Price) As MaxPrice
        From Product 
        Group By ProductType
        ) As MaxByDesc
    On MaxByDesc.ProductType = Product.ProductType

Comments

0

Another way:

SELECT ProductId
     , ProductType
     , Description
     , ( SELECT MAX(price)
         FROM Product pg
         WHERE pg.Description = p.Description 
       ) AS MaxPrice
  FROM Product p

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.