需要高级Sql查询解决方案

时间:2017-05-24 21:58:06

标签: sql

player       team           start_date   end_date  points
John Jacob   SportsBallers  2015-01-01  2015-03-31  100
John Jacob   SportsKings    2015-04-01  2015-12-01  115
Joe Smith    PointScorers   2014-01-01  2016-12-31  125
Bill Johnson SportsKings    2015-01-01  2015-06-31  175
Bill Johnson AllStarTeam    2015-07-01  2016-12-31  200

上表有更多行。我在接受采访时被问到以下问题。

  

1.)对于每位球员,他们在2015-01-01参加哪支球队?

我无法回答这个问题。

  

2.)对于每个球员,我们怎样才能得到他们得分最多的球队?

select team from Players
where points in (select max(points) from players group by player).

请为两者提供解决方案。

2 个答案:

答案 0 :(得分:1)

1

select *  
from PlayerTeams  
where startdate <='2015-01-01' and enddate >= '2015-01-01'  

2

Select player, team, points  
from(  
Select *, row_number() over (partition by player order by points desc) as rank  
From PlayerTeams) as player  
where rank = 1  

答案 1 :(得分:0)

对于#1:

Select Player
      ,Team
From table
Where '2015-01-01' between start_date and end_date

对于#2:

select t.Player
      ,t.Team
from table t
inner join (select Player
                  ,Max(points)
            from table
            group by Player) m
   on t.Player = m.Player
   and t.points = m.points