Flexport OA 面试真题解析:Election(SQL 统计每个政党的获胜席位)

21次阅读
没有评论

Election

Given a database of the results of an election, find the number of seats won by each party. There are some rules to going about this:

  • There are many constituencies in a state and many candidates who are contesting the election from each constituency.
  • Each candidate belongs to a party.
  • The candidate with the maximum number of votes in a given constituency wins for that constituency.

The output should be in the following format: Party Seats_won.

The ordering should be in the order of seats won in descending order.

这道题本质上是一个 SQL 分组统计题:先在每个 constituency 里找出票数最高的 candidate,再把这些获胜者按 party 关联起来,最后统计每个政党拿到的 seat 数,并按 seats_won 降序输出。关键点是要正确处理“每个选区只选票数最高者”的逻辑,通常可以用子查询或窗口函数先筛出每个选区的冠军,再 group by party 计数。

正文完
 0