跨多个列的SQL查询最大值多行

时间:2016-11-03 22:39:54

标签: sql tsql

我需要编写一个sql查询,它将返回每个用户ID具有最大值的行。

在我的表中,我有5列(蓝色,红色,绿色,蓝色,橙色,黄色),用于存储数值。在我的表中,用户可以出现在多行中。

对于每个用户ID,我需要确定5个列中的哪一列(蓝色,红色,绿色,蓝色,橙色,黄色)具有每个用户ID的最高值。我已经厌倦了一些事情,但我被困了。

如果我需要提供其他信息,请告知我们。

见下表enter image description here

3 个答案:

答案 0 :(得分:1)

如果你想获得幻想,你可以在群组中查看Using GROUP BY with ROLLUP, CUBE, and GROUPING SETS,但一个简单的方法是展平列表。您可以使用下面的示例转轴或联合。然后使用row_number获取列表中的第一个。

declare @tbl table (UserId int, Blue int, Red int, Green int, Orange int, yellow int)


insert into @tbl (UserId, Blue, Red, Green, Orange, Yellow)
values
(1, 1,9,4,3,4),
(2, 2,5,4,3,5),
(3, 3,4,9,3,3),
(4, 9,4,6,3,9),
(5, 2,4,5,2,9)
;
with flattenedCte as (
    select UserId, Blue [Count], 'Blue' Color from @tbl
    union
    select UserId, Red [Count], 'Red' Color from @tbl
    union
    select UserId, Green [Count], 'Green' Color from @tbl
    union
    select UserId, Orange [Count], 'Orange' Color from @tbl
    union
    select UserId, Yellow [Count], 'Yellow' Color from @tbl
)
,Sub as (
select
    UserId,
    Color,
    max([Count]) [Max of Count],
    ROW_NUMBER() over (partition by UserId order by max([Count]) desc) [Row number]
    from flattenedCte
        group by UserId,Color
)
select * from Sub where [Row number] = 1

答案 1 :(得分:0)

可以使用案例

select 
   user_id
 , case when (blue > Red AND Blue > Green AND Blue > Orange AND Blue > Yellow) THEN Blue ELSE null END
 , case when (Red > Blue AND Red > Green AND Red > Orange AND Red > Yellow) THEN Red ELSE null END
 , case when (Green > Blue AND Green > Red AND Green > Orange AND Green > Yellow) THEN Green ELSE null END
 , case when (Orange > Blue AND Orange > Red AND Orange > Green AND Orange > Yellow) THEN Orange ELSE null END
 , case when (Yellow > Blue AND Yellow > Red AND Yellow > Green AND Yellow > Orange) THEN Yellow ELSE null END
from my_table 

答案 2 :(得分:0)

在您的情况下,如果与子表格配合使用可能会有所帮助,那么可能会有更好的解决方案。

这篇文章here可能会帮助您。