Skip to content
Advertisement

How to get the column name of the result of a least function?

I have an employee table that looks like this:

I needed to get the minimum value and maximum value of questions where the id is equal to 4. In this case, I needed 5 and 25 returned. I acheived that using the following query:

But what this doesn’t return is the question id. How can I adjust my query to show that q2 is the minimum and q4 is the maximum? I know I could write a big case statement, but I also feel like it could be accomplished using a join but I can’t figure it out.

Note: This is for a postgresql database, but I tagged MySQL as well because I know it also supports the LEAST and GREATEST functions. If the solution is very different for both, then I will remove this note and make a separate question.

EDIT

I have an SQL Fiddle already.

Advertisement

Answer

You can use a case statement:

(Note: it will lose information over ties.)

If you’re interested in ties, approaching it with a subquery and arrays will do the trick:

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