I have an employee table that looks like this:
| id | name | q1 | q2 | q3 | q4 |
+----+------+----+----+----+----+
| 1 | John | 20 | 30 | 10 | 4 |
| 2 | Ram
You can use a case
statement:
CASE
WHEN LEAST(q1, q2, q3, q4) = q1 THEN 'q1'
WHEN LEAST(q1, q2, q3, q4) = q2 THEN 'q2'
WHEN LEAST(q1, q2, q3, q4) = q3 THEN 'q3'
ELSE 'q4'
END as minQuestion
(Note: it will lose information over ties.)
If you're interested in ties, approaching it with a subquery and arrays will do the trick:
with employee as (
select id, q1, q2, q3, q4
from (values
(1, 1, 1, 3, 4),
(2, 4, 3, 1, 1)
) as rows (id, q1, q2, q3, q4)
)
SELECT least(q1, q2, q3, q4),
array(
select q
from (values (q1, 'q1'),
(q2, 'q2'),
(q3, 'q3'),
(q4, 'q4')
) as rows (v, q)
where v = least(q1, q2, q3, q4)
) as minQuestions
FROM employee e
WHERE e.id = 1;