I have the following query:
SELECT * FROM quotes
INNER JOIN quotes_panels ON quotes.wp_user_id = quotes_panels.ID
WHERE quotes.created >= '$startDate'
AND quotes.created <= '$endDate' AND quotes.wp_user_id != '0'
This query can produce multiple rows from the same user (quotes.wp_user_id) but I only want to show the row which has the biggest roof area (quotes.roofarea).
However when I added GROUP BY quotes.wp_user_id it automatically takes the lowest quotes.ID row rather than the row with the biggest quotes.roofarea. When adding ORDER BY quotes.roofarea DESC to the end of the query it ordered the entire results not just the results of the "GROUP BY".
Can anyone assist with getting the desired results for the query?
Thanks
You have to order the rows before you group them.
SELECT * FROM (SELECT * FROM quotes
INNER JOIN quotes_panels ON quotes.wp_user_id = quotes_panels.ID
WHERE quotes.created >= '$startDate'
AND quotes.created <= '$endDate' AND quotes.wp_user_id != '0'
ORDER BY quotes.roofarea DESC) a
GROUP BY a.wp_user_id
In MySQL GROUP BY
is done before ORDER BY
, so you would need to do this in two queries:
SELECT * FROM
(SELECT * FROM quotes
INNER JOIN quotes_panels ON quotes.wp_user_id = quotes_panels.ID
WHERE quotes.created >= '$startDate'
AND quotes.created <= '$endDate' AND quotes.wp_user_id != '0'
ORDER BY quotes.roofarea DESC) AS subset
GROUP BY subset.wp_user_id
You have to add an aggregate function like this:
SELECT *, MAX(quotes.roofarea) FROM quotes
INNER JOIN quotes_panels ON quotes.wp_user_id = quotes_panels.ID
WHERE quotes.created >= '$startDate'
AND quotes.created <= '$endDate' AND quotes.wp_user_id != '0'
GROUP BY quotes.wp_user_id
Read more about it here:
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
Try this
SELECT * FROM quotes
INNER JOIN quotes_panels ON quotes.wp_user_id = quotes_panels.ID
WHERE quotes.created >= '$startDate'
AND quotes.created <= '$endDate' AND quotes.wp_user_id != '0'
AND quotes.roofarea = (SELECT MAX(q.roofarea) FROM quotes q WHERE q.wp_user_id = quotes.wp_user_id)
GROUP BY quotes.wp_user_id
Check Now
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.