Skip to content
Advertisement

Summarize unique column in row

I’m new to Firebird and need your help.

I have a stored procedure with following reduced output:

Player Team Number
Reus Ahlen 18
Lewandowski Posen 19
Reus MG 11
Reus BVB 11
Lewandowski BVB 9
Haaland BVB 9

I want to summarize the Players and transform Team&Number to a new column.

The output should be:

Player Station 1 Station 2 Station 3
Reus Ahlen 18 MG 11 BVB 11
Lewandowski Posen 19 BVB 9
Haaland BVB 9

I am using Firebird 2.5.8

Advertisement

Answer

For the remainder of this answer, I’m using the following setup:

The examples assume that the player name is sufficient to uniquely identify the player.

Because of the nature of Firebird’s DSQL dialect and implementation of query execution, the number of ‘station’ columns is fixed. In this example, I’m using three, like your question, but this can be extended to more columns if necessary. In Firebird 2.5, generating the desired pivot table is messy, and will likely not perform well.

A basic, pure SQL solution, would be something like:

In this example, we determine the unique players, and then select the first, second and third station using a subquery using rows (you can also use first/skip, or, in Firebird 3.0 and higher, offset/fetch)

An alternative, which likely performs better, is using a stored procedure or execute block, but the code does get more complex.

This iterates over the rows, populating the output columns of the execute block, outputting them when the next player is found.

On the other hand, in Firebird 4.0, you could do something like:

Using NTH_VALUE window function:

Or using filtered aggregate functions:

Using a lateral join:

This is is similar to the first example, but pushing down the selection of the stations into the lateral join (a feature introduced in Firebird 4.0).

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