Skip to content
Advertisement

MySQL: How to compare multiple field value of a row and get matched or lowest one?

I have a MySQL table (below):

enter image description here

I can fetch the min or max of the column values simply but my problem is:

  1. If any 3 or more fields value matched then fetch that value (if 3 fields values matched more than one value then the lowest of those values), for row #1 2100 will be the output and for row#3 55 will be the output.

  2. If no field value matched with a minimum of 3 fields the lowest value of the entire row will be fetched, for row# 2 the output will be 1900.

I can use IF (e.g. select if(col1 = col2, col1, col2) from table) in select but I didn’t find a solution for this situation. Can anyone help to write a MySQL query for this?

Thanks in advance!

Advertisement

Answer

You can use this query to get the results you want. It uses two nested subqueries: the first unpivots the data into a single column; the second then counts how many of each column value occur for a given ID value. The outer query then tests the maximum of the counts; if it is >= 3 then the minimum value which has a count of 3 or more is chosen, otherwise the minimum column value is chosen as the minimum column:

Output (for your sample data):

Demo on SQLFiddle

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement