Home » Mysql » How do I select the longest 'string' from a table when grouping

How do I select the longest 'string' from a table when grouping

Posted by: admin November 1, 2017 Leave a comment

Questions:

Example:

SELECT partnumber, manufacturer, condition, SUM(qty), AVG(price), description FROM parts

WHERE [something]

GROUP BY partnumber, manufacturer, condition

I have some descriptions that are blank, and there can be many partnumber, manufacturer, condition values, and on the group it seems to take the first description available, which can be blank. Id like to get the longest description available.

i tried this:

MAX(LENGTH(description)) 

however that returns the number of characters in the string. Is it possible to do what im trying to do in MySQL?

Answers:

Try ORDER BY LENGTH(description) DESC and use LIMIT 1 to only get the largest.

Questions:
Answers:
ORDER BY LENGTH(description) DESC LIMIT 1

This will sort the results from longest to shortest and give the first result (longest.)

Questions:
Answers:
SELECT   partnumber, manufacturer, `condition`, SUM(qty), AVG(price), description
FROM     parts
WHERE    [something] AND LENGTH(description) = (
           SELECT MAX(LENGTH(description))
           FROM   parts AS p
           WHERE  p.partnumber   = parts.partnumber
              AND p.manufacturer = parts.manufacturer
              AND p.condition    = parts.condition
         )
GROUP BY partnumber, manufacturer, `condition`

Questions:
Answers:

It seems i answered my own question, MAX(description) seems to work just fine.