获取具有行sql中最大值的列名

时间:2012-05-24 17:41:03

标签: mysql sql max

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

enter image description here

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

enter image description here

我尝试过几件事,搜索过很多但不知道该怎么做。任何人都可以帮助我吗?

4 个答案:

答案 0 :(得分:4)

这应该这样做:

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

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

答案 1 :(得分:1)

一种非常简单的方法如下所示

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;

答案 2 :(得分:0)

PL / SQL,也许吧?设置user_id,查询表,将返回的行存储在列名和值的nx2数组中(其中n是列数),并根据值对数组进行排序。

当然,正确的做法是以@octern建议的方式重新设计您的数据库。

答案 3 :(得分:0)

这将让您开始从单行中的多个列中获取最高值的概念(修改您的特定表 - 我创建了一个假的)。

create table fake 
(
  id int Primary Key,
  col1 int,
  col2 int,
  col3 int,
  col4 int 
)
insert into fake values (1, 5, 9, 27, 10)
insert into fake values (2, 3, 5, 1, 20)
insert into fake values (3, 89, 9, 27, 6)
insert into fake values (4, 17, 40, 1, 20)

SELECT *,(SELECT Max(v) 
FROM (VALUES (col1), (col2), (col3), (col4) ) AS value(v))
FROM fake