0

let's say I have a table like so:

Store    | Item   | Price  
store01  | Apple  | 2.50  
store01  | Pear   | 3.00
store01  | Banana | 3.11  
store02  | Apple  | 2.50  
store02  | Pear   | 2.00
store03  | Banana | 3.10  

and I just want a query that lists all the stores and names the most expensive item in that store. So I need something like this:

Store   | Item  
store01 | Banana 
store02 | Apple 
store03 | Banana  

I tried something like so:

SELECT "Store",
       (case when (max ("Price") = "Price") then "Item" end) as  "Max price Item"   
FROM Table 
group by "Price","Item","Store"; 

but the result of that is just:

Store   | Max price Item 
store01 | Apple 
store01 | Pear
store01 | Banana
store02 | Apple
store02 | Pear
store03 | Banana

I am running on dashDB.

Mike Pala
  • 766
  • 1
  • 11
  • 39

3 Answers3

1

You should use this

SELECT t.Store,
    t.Item
FROM Table t
INNER JOIN
    (SELECT
        Store,
        MAX(Price) AS max_price
    FROM
        Table 
    GROUP BY 
        Store
    ) mt
ON 
    mt.Store = t.Store
    AND mt.max_price = t.Price;

Or other way could be:

SELECT t.Store,
    t.Item
FROM Table t
WHERE (Store, Price) IN
    (SELECT
        Store,
        MAX(Price) AS max_price
    FROM
        Table 
    GROUP BY 
        Store
    );
Pham X. Bach
  • 5,284
  • 4
  • 28
  • 42
1

Try with the below query

SELECT Store,Item
  FROM YourTable T,
        (SELECT Store,max(Price) MPrice
         FROM YourTable
          GROUP BY Store
         ) AS T1
  WHERE T1.Store=T2.Store AND T1.Price=T2.MPrice
Unnikrishnan R
  • 4,965
  • 1
  • 12
  • 21
1

The following should do the trick:

 SELECT Store, MAX(Price) FROM Table
 GROUP BY Store

Or

 SELECT
  b.Store,
  MAX(b.Price) as MaxPrice,
  MAX(b.Item) as Item
FROM Table b
INNER JOIN (SELECT 
              Store,
              MAX(Price) as MaxPrice
            FROM Table
            GROUP BY Store) a ON 
a.Store = b.Store AND a.MaxPrice = b.Price
GROUP BY b.Store

Sample inputs and outputs:

sample_input

sample_output

AT-2017
  • 3,114
  • 3
  • 23
  • 39