Skip to content
Advertisement

PostgreSQL string_agg, default value when no value found

I have a table like this:

that I transform in this format I need:

with this query:

So far so good, assuming all systems_ids have the same number of dates. However, this might not be the case. Let’s add a row to the db:

My result now looks like this:

This is really problematic because I rely on the order of the numbers to represent different systems_ids.

How can I fill a default value when there’s not a value to aggregrate?

I need row 6 in my result to look like this [6, 0, 1234] or this [6, NaN, 1234] or whatever is considered a good practice would be fine. Though it is paramount that the order ["date", "system_id_1", "system_id_2"] is always respected.

Alternatively, it’d be ok to skip the whole row. To do so, I could call

And somehow exclude all rows where dates_count is not equal to MAX(dates_count). But how?

Advertisement

Answer

You can generate the rows using a cross join. Then bring in the data and aggregate:

I would also suggest that you use arrays rather than strings for this purpose.

EDIT:

Or, to skip the incomplete rows:

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