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

nr7wwzry  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(211)

所以我在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

我想将每个记录的用户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
lstz6jyr

lstz6jyr1#

使用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
7gs2gvoe

7gs2gvoe2#

假设没有值 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;
mkh04yzy

mkh04yzy3#

使用 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

相关问题