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:

我的数据库中有一个表,用于存储新闻文章的类别,每次用户阅读一篇文章时,它都会增加相关列中的值。是这样的:

Now I want to execute a query where I can get the column names with the 4 highest values for each record. For example for user 9, it would return this:

现在,我想执行一个查询,在那里我可以得到每个记录的4个最高值的列名。例如,对于用户9,它将返回:

I've tried several things, searched a lot but don't know how to do it. Can anyone help me?

我尝试过很多东西,搜索过很多,但是不知道怎么做。谁能帮我吗?

4 个解决方案

#1


3

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

演示:http://www.sqlfiddle.com/ ! 2 / ff624/11

更多相关文章

  1. 检索每n行的最高值
  2. 在for循环中生成的数字如何输出它们,就像它们的最高值是1和最低0

随机推荐

  1. bootstrap-multiselect 多选实例代码
  2. 详解可选参数和命名参数实例
  3. 分享一个IoC入门教程实例
  4. [转]Composite Keys With WebApi OData
  5. 总结EF通用数据层封装类实例详解
  6. [转]Support Composite Key in ASP.NET W
  7. 学习ASP.NET Core 2遇到的问题分享
  8. 使用ConcurrentDictionary多线程同步字典
  9. 浅谈WPF之Binding表达式
  10. 一个很强大的控件--PropertyGrid