Calculating the largest side of a 3d object - MySQL function to select second greatest value

StackOverflow https://stackoverflow.com/questions/12279537

  •  30-06-2021
  •  | 
  •  

Domanda

I have three fields for width, height and depth. Let's say I have these values

width = 5
height = 0.1
depth = 3

I would like to filter out greatest two values from these values and do maths for two dimensions to find out the largest side.

It should be a * b

a = GREATEST(width, height, depth) /* greatest value selected */
b = GREATEST(width, height, depth) /* <-- select the second greatest value here */

The reason why I can't ignore width here is that I don't know which one of the width, height, depth has the max value and selected as the value of a

EDIT: Didn't mention that these fields may contain NULL values

EDIT: The table contains dimensions for 2D objects to. In some cases depth may not exist. It can be NULL

È stato utile?

Soluzione

If the types are float, you may get rounding errors with this:

a = GREATEST(width, height, depth)   /* greatest value selected */
c = LEAST(width, height, depth)
b = width + height + depth - a - c   /* middle value */

Another route:

b = ( SELECT width AS side
      FROM tableX
      WHERE pk = externalTable.pk
    UNION ALL
      SELECT height
      FROM tableX
      WHERE pk = externalTable.pk
    UNION ALL
      SELECT depth
      FROM tableX
      WHERE pk = externalTable.pk
    ORDER BY side DESC
      LIMIT 1 OFFSET 1
    ) 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top