Get column name which has the max value in a row sql

前端 未结 4 841
孤城傲影
孤城傲影 2021-01-20 22:47

I have a a table in my database where I store categories for newsarticles and each time a user reads an article it increments the value in the associated column. Like this:<

4条回答
  •  不知归路
    2021-01-20 23:22

    A very simple way of doing this is shown below

    select userId, substring_index(four_highest,',',1) as 'highest value', substring_index(substring_index(four_highest,',',2),',',-1) as '2th highest value',  substring_index(substring_index(four_highest,',',3),',',-1) as '3 rd highest value',  substring_index(four_highest,',',-1) as '4th highest value'   from
    (
    select userid, convert(group_concat(val) using utf8) as four_highest from
    (
    select userId,Buitenland as val,'Buitenland' as col from test where userid=9 union
    select userId,Economie as val,' Economie' as col from test where   userid=9 union
    select userId,Sport as val ,'Sport' as col from test where  userid=9 union
    select userId,Cultuur as val,'Cultuur' as col from test where userid=9 union
    select userId,Wetenschap as val,'Wetenschap' as col from test where userid=9 union
    select userId,Media as val,'Media' as col from test where  userid=9 order by val desc limit 4
    ) inner_query
    )outer_query;
    

提交回复
热议问题