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

前端 未结 4 837
孤城傲影
孤城傲影 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:10

    This should do it:

    select
      userid,
      max(case when rank=1 then name end) as `highest value`,
      max(case when rank=2 then name end) as `2nd highest value`,
      max(case when rank=3 then name end) as `3rd highest value`,
      max(case when rank=4 then name end) as `4th highest value`
    from
    (
      select userID, @rownum := @rownum + 1 AS rank, name, amt from (
        select userID, Buitenland as amt, 'Buitenland' as name from newsarticles where userID = 9 union
        select userID, Economie, 'Economie' from newsarticles where userID = 9 union
        select userID, Sport, 'Sport' from newsarticles where userID = 9 union
        select userID, Cultuur, 'Cultuur' from newsarticles where userID = 9 union
        select userID, Wetenschap, 'Wetenschap' from newsarticles where userID = 9 union
        select userID, Media, 'Media' from newsarticles where userID = 9
      ) amounts, (SELECT @rownum := 0) r
      order by amt desc
      limit 4
    ) top4
    group by userid
    

    Demo: http://www.sqlfiddle.com/#!2/ff624/11

提交回复
热议问题