2014-03-26 26 views
0

我试图找出行是否具有组中的最大值。这里是非常简单的例子:检查该行是否具有组中的最大值

数据

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

你也可以做到这一点使用一个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 
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
但如果你的表是巨大的,并没有propriate索引的性能可能会很差
另一种方式是按组获得最大的值到表变量或临时表,然后将其加入到原始表。

相关问题