2014-03-26 30 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索引的性能可能會很差
另一種方式是按組獲得最大的值到表變量或臨時表,然後將其加入到原始表。

相關問題