插入具有最高值的列的列名

时间:2018-06-19 15:16:18

标签: mysql sql database

所以我在MySQL中有下表:

user_id  column1  column2  column3  column4  column5
-------  -------  -------  -------  -------  -------
1        1        15       12       20       25
2        5        9        6        15       10
3        7        12       21       9        17

我想将user_id以及每条记录具有最高值的列名插入到新表中,如下所示:

user_id  highest_val
-------  -----------
1        column5
2        column4
3        column3 

有人可以帮我吗?谢谢!

到目前为止,我已经设法仅使用以下查询获取列的值,而不是列名称本身:

insert into table2 (user_id, highest_val) SELECT user_id, GREATEST(column1, column2, column3, column4, column5) FROM table1

3 个答案:

答案 0 :(得分:2)

假设没有值是NULL,则可以使用case表达式:

select t.*,
       (case when column1 = greatest(column1, column2, column3, column4, column5) then 'column1'
             when column2 = greatest(column1, column2, column3, column4, column5) then 'column2'
             when column3 = greatest(column1, column2, column3, column4, column5) then 'column3'
             when column4 = greatest(column1, column2, column3, column4, column5) then 'column4'
             when column5 = greatest(column1, column2, column3, column4, column5) then 'column5'
      end) as greatest_column             
from t;

您也可以这样表达:

select t.*,
       (case greatest(column1, column2, column3, column4, column5)
             when column1 then 'column1'
             when column2 then 'column2'
             when column3 then 'column3'
             when column4 then 'column4'
             when column5 then 'column5'
      end) as greatest_column             
from t;

答案 1 :(得分:2)

使用CASE表达式获取相应的列名。

INSERT INTO table2 (user_id, highest_val)
SELECT user_id,
    CASE GREATEST(column1, column2, column3, column4, column5)
        WHEN column1 THEN 'column1'
        WHEN column2 THEN 'column2'
        WHEN column3 THEN 'column3'
        WHEN column4 THEN 'column4'
        ELSE 'column5'
    END AS highest_val
FROM table1

答案 2 :(得分:0)

将CTE与联合结合使用,如下所示:

with cte as (select user_id, column1 as col, 1 [group] 
from #temp
union all
select user_id, column2, 2 [group]
from #temp
union all
select user_id, column3, 3 [group]
from #temp
union all
select user_id, column4, 4 [group]
from #temp
union all
select user_id, column5, 5 [group]
from #temp) 


select a.user_id, 'column'+cast([group] as varchar(max)) highest_val from cte a join
(select user_id, max(col) col from cte
group by user_id )b
on a.user_id=b.user_id and a.col=b.col