2017-05-24 76 views
-3
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 

上表中有更多行。在面試中我被問到了下面的問題。需要高級Sql查詢解決方案

1.)對於每個球員,他們在2015-01-01參賽哪支球隊?

我無法回答這個問題。

2.)對於每個球員,我們怎麼能得到他們得分最高的球隊?

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

請,兩種解決方案。

回答

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 
+0

選擇團隊從玩家 指向哪裏(按隊員分組選擇最大(點數)) - 這是錯誤的嗎? – Drishti

+0

嗨Degan ...感謝您的回覆。我對第一個查詢有疑問,我們可以用這樣的方式寫一個查詢:「Where'2015-01-01'start_date和end_date之間」。我總是寫下如下查詢:「2015-01-01'和'2015-03-01' – Drishti

+0

之間的Start_date是,您可以在」start_date和end_date之間「編寫查詢」Where'2015-01-01「。 「從選手隊伍中選擇隊伍(從隊員中選擇最大(點數))」查詢會發現擁有一名隊員的隊伍得分與任何隊員的最高分數相同。 – Degan

1
select * 
from PlayerTeams 
where startdate <='2015-01-01' and enddate >= '2015-01-01' 
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