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

后端 未结 4 1021
北海茫月
北海茫月 2021-01-27 03:24

I have an employee table that looks like this:

| id | name | q1 | q2 | q3 | q4 |
+----+------+----+----+----+----+
| 1  | John | 20 | 30 | 10 | 4  |
| 2  | Ram           


        
4条回答
  •  长发绾君心
    2021-01-27 04:04

    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;
    

提交回复
热议问题