2013-11-25 60 views
0

我在SQL中包含此餐桌投票。在SQL中計票並按順序降序

表:

enter image description here

現在,我想要做的是數都一樣MealId與對方,並責令其按降序排列。

例如(ID | MealId |用戶ID | VoteDate):

1 | 13 | 1 | somedate 

2 | 1 | 2 | somedate 

3 | 3 | 1 | somedate 

4 | 13 | 3 | somedate 

現在,經過計算就應該是這樣的:

2 //Here are the MealId's that are equal to 13 
1 //Here are the MealId's that are equal to 1 or 3, because there is only 1 vote for that Meal 
1 //Here are the MealId's that are equal to 1 or 3, because there is only 1 vote for that Meal 

注意:它不會有顯示該投票計數:「2,1,1」,我只想按降序排列投票。包含大部分選票的膳食應該是最重要的。

回答

1

使用窗口骨料(COUNT)得到計數數據到行旁邊的其他數據,然後只是簡單ORDER BY

;With TotalVotes as (
    select *,COUNT(*) OVER (PARTITION BY MealId) as Cnt 
    from UnnamedTable 
) 
select * from TotalVotes ORDER BY Cnt desc,MealId 
+0

這工作,謝謝。等待倒計時以標記爲已接受的問題。 – etritb