I’m trying to figure out how to run a query that would go something like this:
$query = "SELECT RegPrice, OnSalePrice
Math.abs(Math.max(100 - (OnSalePrice) / (RegPrice) * 100)) AS DiscountIS
FROM Products";
So it would take RegPrice & OnSalePrice and give me the percentage of the discount and return it as DiscountIS along with the other 2 values.
Query TWO & Get back THREE.
Any ideas?? Thanks!
Your query as written is syntactically correct except that you’re missing a comma after OnSalePrice and you shouldn’t put
Math.in front of abs or max. You should also probably end it with a semicolon, but that doesn’t usually matter. So, the correct query would be:(I’ve also capitalized ABS and MAX, but that’s just a style choice. SQL ignores case in all commands and functions.)
However, there’s problem with this query, which is that MAX is an aggregate function, so it returns the maximum value for the whole table. As such, when using aggregate functions, like MAX, you can’t also select other attributes. So if you want each item to show its RegPrice, OnSalePrice, and the discount, the correct way to do this is to simply leave out MAX. (I suspect that this is what you want to do, since the Math.max function only gives the maximum of its arguments. But I’m not sure because you’ve only given it one argument in this case.)
If you actually want to know the regular price, sale price, and discount of whichever one has the biggest discount, that’s a slightly more complex query which has to be handled by doing a SELECT within a SELECT.
It should be noted, though, that as written, in any version, if OnSalePrice is bigger than RegPrice, then this will still show as a discount and that if the RegPrice is zero, a division by zero will result.