Question

I need to return only results that have the highest percentage of change. Table looks like

item      price1    price2
a         1         2
b         3         5
c         2         3

I would only want it to return a, like this:

item      price1    price2   percent_change
a         1         2        200%

I tried this

   select item, price1, price2, max(a.mPrice) as my_output from (select item, 
  ((price2-price1)/price1) * 100 as mPrice from table) a

but it says the indetifier is invalid (assuming that's a.mPrice). I've tried using having to only check for the max, but that didn't work, it still return all the results.

I feel like I'm missing something really obvious but I can't think of what it is. I'm guessing that using max(a.mPrice) wouldn't actually get the max like I need, but I'm not sure what else to do.

Was it helpful?

Solution 3

I figured it out.

select item, price1, price2, ((price2 - price1)/price1) * 100 as my_output from table
group by item, price1, price2
having ((price2 - price1)/price1) * 100 = (select( max(((price2 - price1)/price2) * 100)) from table)

It's messy, but does what I need it to.

OTHER TIPS

Your table a does not have anything but item and mPrice so fetching price1 and price2 in outer query does not work.

But you can do it even without such subquery

SELECT item, price1, price2, ((price2-price1)/price1)*100 as growth
FROM products
ORDER BY growth DESC 
LIMIT 1;

First, choose all three attributes and calculate growth, then order by growth descending and only take the top value.

Fiddle: http://sqlfiddle.com/#!2/16b7c/7

Simple query if you want only max percentage

SELECT item, price1, price2, MAX(((price2-price1)/price1) * 100) percent_change FROM items
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top