I have a need to get the max number of records from a table and concatenate that number at the end of the field name, starting at 1 and ending at the max number of records:
field1 | cnt |
---|---|
Car | 4 |
Truck | 3 |
The final results need to be exportable in the format:
Car|1
Car|2
Car|3
Car|4
Truck|1
Truck|2
Truck|3
I cant use RAISE
as I need more than a message in this instance. It has to be data output so the results can be used downstream.
3
Answers
If that’s your table (matching your description):
Then
row_number()
works:If that’s your table (your sample data):
Then
generate_series()
does the job:fiddle
Neither loop nor recursion are needed either way.
Below are two approaches to achieving the described results. The first uses a recursive common table expression (CTE) and is a close analog to loops in procedural languages. When working with databases, it is useful to break away from procedural thinking and instead embrace set based approaches. A set based approach is demonstrated in the second query.
Let’s use a temporary table with integers until …. well basically the max number that will be needed, like (
SELECT max(cnt) FROM mytable;
), but let’s stick to10
for now:Then you can do an INNER JOIN:
or, if we really need the desired output:
see: DBFIDDLE