我在SQL中有这个包含膳食投票的表。
表:
现在,我想做的是相互计算所有相同的MealId,并按降序排序。
例如(Id | MealId | UserId | 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”,我只想按降序排序。包含大部分选票的膳食应该在最重要的位置。
答案 0 :(得分: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