sql >> Database >  >> RDS >> Mysql

Kolomnaam ophalen met de maximale waarde in een rij sql

Dit zou het moeten doen:

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



  1. Hoe werkt MySQL CASE?

  2. Hoe MySQL te beveiligen:deel één

  3. SEC_CASE_SENSITIVE_LOGON Verouderd in 12c

  4. Mysql-wachtwoord wijzigen in Docker-container