[英]SQL - How do I return the most recent occurence in a column along with other aggregated columns?
(BigQuery SQL) I have three tables of Formula 1 data - results, races, drivers. (BigQuery SQL)我有三个一级方程式数据表——结果、比赛、车手。 I am trying to compile a summary that includes the driver, a count of their top 5 finishes, a count of their podium finishes, their total wins, most recent race, and most recent win.
我正在尝试编写一份摘要,其中包括车手、他们的前 5 名完成次数、他们登上领奖台的次数、他们的总胜利、最近的比赛和最近的胜利。 I am struggling with the most recent win.
我正在为最近的胜利而苦苦挣扎。
The three tables have the following columns:这三个表具有以下列:
results:结果:
races:种族:
drivers:司机:
I can get every piece of information I need except for the most recent win with the following query:我可以通过以下查询获得我需要的每条信息,除了最近的胜利:
SELECT
drivers.driverId,
driverRef,
SUM(IF(results.position <=5,1,0)) AS top_five_finishes,
SUM(IF(results.position <=3,1,0)) AS podium_finishes,
SUM(IF(results.position = 1,1,0)) AS number_of_wins,
MAX(races.date) AS most_recent_race,
FROM `formula1.all_results` AS results
FULL JOIN `formula1.all_drivers` AS drivers ON results.driverId = drivers.driverId
FULL JOIN `formula1.all_races` AS races ON results.raceId = races.raceId
GROUP BY driverRef, driverId
ORDER BY number_of_wins DESC
Which returns:返回:
I am struggling to include the most recent win.我正在努力包括最近的胜利。 I have tried adding the following statement to the above query:
我尝试将以下语句添加到上述查询中:
(select max(races.date)
from
`formula1-356612.formula1_project.all_results` AS results
full join `formula1-356612.formula1_project.all_drivers` AS drivers ON results.driverId = drivers.driverId
full join `formula1-356612.formula1_project.all_races` AS races ON results.raceId = races.raceId
where results.position = 1
) as most_recent_win
But that simply returns the most recent race in the entire table.但这只会返回整个表格中最近的比赛。 I have tried creating a subquery to find the most recent win but it returns every win, not the most recent:
我尝试创建一个子查询来查找最近的胜利,但它返回每一次胜利,而不是最近的:
select
results.driverId as driver_id,
races.date as date_of_win,
races.name as track_name,
results.position as place
from `formula1.all_results` as results
join `formula1.all_races` as races on results.raceId = races.raceId
where results.position = 1
group by driver_id, date_of_win, track_name, place
order by date_of_win desc
And additionally I am unsure how I would join that information to the existing query.此外,我不确定如何将这些信息加入到现有查询中。
In order to get one most recent win:为了获得最近的一场胜利:
SELECT
.....
</ Your query with necessary fields and conditions>
....
ORDER BY date_of_win DESC
LIMIT 1
I've discovered the answer.我已经找到了答案。 It's a simple statement:
这是一个简单的声明:
max(if(results.position = 1, races.date, null)) as most_recent_win
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.