[英]Insert the Column Name of the Column with the Highest Value
所以我在 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
假設沒有值為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;
使用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
使用 CTE 和 union,如下所示:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.