检查行是否具有组中的最大值

时间:2014-03-26 19:57:16

标签: sql sql-server tsql

我试图找出某一行是否具有组中的最大值。这是一个非常简单的例子:

数据

VoteCount   LocationId  UserId
3           1           1
4           1           2
3           2           2
4           2           1

伪查询

select 
    LocationId,
    sum(case 
          when UserId  = 1  /* and has max vote count*/ 
            then 1 else 0 
        end) as IsUser1Winner,
    sum(case 
          when UserId  = 2  /* and has max vote count*/ 
            then 1 else 0 
        end) as IsUser2Winner
from LocationVote
group by LocationID

它应该返回:

LocationId  IsUser1Winner   IsUser2Winner
1           0           1
2           1           1

我也找不到在这里生成动态列名的方法。编写此查询的最简单方法是什么?

2 个答案:

答案 0 :(得分:2)

您也可以使用Case声明

执行此操作
WITH CTE as 
    (SELECT 
        MAX(VoteCount) max_votes
        , LocationId
    FROM LocationResult
    group by LocationId
    )
    SELECT 
        A.LocationId 
        , Case When UserId=1
            THEN 1
            ELSE 0
            END IsUser1Winner   
        , Case when UserId=2
            THEn 1
            ELSE 0
            END IsUser2Winner   
    from LocationResult A
    inner join 
    CTE B
    on A.VoteCount = B.max_votes
    and A.LocationId = B.LocationId

答案 1 :(得分:0)

试试这个:
select *
from table t
cross apply (
select max(votes) max_value
from table ref
where ref.group = t.group
)votes
where votes.max_value = t.votes
但如果你的桌子很大并且没有专有的索引,那么性能可能会很差 另一种方法是按组将最大值获取到表变量或临时表中,然后将其连接到原始表。