To register for an Internet.com membership to receive newsletters and white papers, use the Register button ABOVE.
To participate in the message forums BELOW, click here
SELECT article, MAX(price) AS price
FROM shop
GROUP BY article
That would work just fine, but what if I want to see who the dealer is ? If I try to just insert 'dealer' in the SELECT statement, it won't show me the right dealer, just the first one it finds in that particular group (like this:)
SELECT article, MAX(price) AS price, dealer
FROM shop
GROUP BY article
You are using a version that does not support subqueries. Anyway, I got to thinking, that query would only return the article and dealer of the priciest article. You need a more complicated query.
Create a temporary table that contains two columns:
CREATE TEMPORARY TABLE tmpshop (
article INT(4) UNSIGNED ZEROFILL DEFAULT '0000' NOT NULL,
price DOUBLE(16,2) DEFAULT '0.00' NOT NULL,
);
Then execute this query:
INSERT INTO tmpshop SELECT article, MAX(price)
FROM shop GROUP BY article;
Now you can join the two tables and get the article, price and dealer:
SELECT a1.article, a1.price, a2.dealer
FROM tmpshop a1, tmpshop a2
WHERE a1.article = a2.article
AND a1.price = a2.price;
This query will return what you want, but be careful because it will return multiple rows for an article if the dealers have the same price.
The HAVING clause on you query needs to be:
HAVING price = MAX(price)
But this will not do what we are looking for. This will only return the most expensive article and its dealer.
Well, I'm a big fan of simple solutions And the simplest thing to do now, is to wait for a stable release wich supports subselect. The current 4.1 is still only a alpha release ..
SELECT article,
SUBSTRING( MAX( CONCAT(LPAD(price,6,'0'),dealer) ), 7) AS dealer,
0.00+LEFT( MAX( CONCAT(LPAD(price,6,'0'),dealer) ), 6) AS price
FROM shop
GROUP BY article;
Thanks to Csaba Gabor in the messages following the tutorial on the page listed in the previous post, there is a really simple (and quite efficient way to do it). Use the query:
SELECT shop.*
FROM shop LEFT JOIN shop s2
ON shop.article = s2.article AND shop.price < s2.price
WHERE s2.article IS NULL
This is a much more elegant solution that uses a self join to limit the results. Thanks Csaba.