Skip to content
Advertisement

Tricky MySQL view

I am finding it very difficult to create a view in MySQL, and hope someone could help me out. This is the schema of my db:

This database collects a series of football games and many characteristics for each one, as well as all the teams and the seasons. Thanks to this view (https://stackoverflow.com/a/70794440/17987986), I am able to generate the points, the goals scored as well as those conceded for each season:

Which results in the following:

View Columns are, in order: season, eam, TGS (team golas scored), TGC (team goals conceded)

This is great, but what I need now is to generate the rankings. Ideally, I’d like to have something like the following:

One main difficulty is that, as you can see, ranking are from year 14 (season 2014-2015). Therefor, this data is not present in the db. Although this is a bad thing, is it possible to hardcode it inside the view? I always need the data of the year before each game, so adding older games would just recreate the problem… Also, the current season should be excluded (in the example, see it as if the current season is 2020-2021). Any help or suggestion is appreciated!

Note

I know the db structure is probably not the best, but I have to stick with it for now…

Advertisement

Answer

Why not just calculate the rank for each team / season within the current view. Now you can join with that for any rank (and for any season) you wish, as needed.

If you need the previous year rank, we can use LAG to do that, in a subsequent expression, or just join based on some expression related to the year.

Notice the RANK expression in the select list.

The fiddle

The suggestion (for MySQL 8.0+):

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement