Reputation: 5
I am new to SQL and attempting to display a max value from a column as well as display a separate column from the same table, however, my query doesn't work.
Here is my code:
SELECT ProductName, ProductPrice, MAX(ProductPrice) AS MostProfitable
FROM tblProducts;
I receive this error:
"Your query does not include the specified expression 'ProductName' as part of an aggregate function."
Please Help!
Upvotes: 1
Views: 113
Reputation: 136
None of the functions of column would work until you GROUP your rows.
That is, your MAX() function will not work because you have not used GROUP.
Here is the SQL that should work:
SELECT ProductName, ProductPrice, MAX(ProductPrice) AS MostProfitable
FROM tblProducts GROUP BY ProductName;
I would suggest you to add your Product ID in your SQL query and GROUP the query on it. But for the instance, I have grouped your query on ProductName.
Remember, its not professional. Because different products having same name will also be combined to show one MAX value.
Upvotes: 0
Reputation: 633
You don't need any aggregation function just get it like below:
SELECT TOP(1) ProductName, ProductPrice
FROM tblProducts
ORDER BY ProductPrice DESC;
Upvotes: 0
Reputation: 1271141
A simple method to get all the columns to use ORDER BY
and TOP
:
SELECT TOP (1) p.*
FROM tblProducts as p
ORDER BY p.ProductPrice DESC;
Note that TOP
in MS Access can return more rows if there are ties. If you want only one row, then include an additional key in the ORDER BY
to prevent ties:
ORDER BY p.ProductPrice DESC, p.ProductName;
Upvotes: 1