I have a query that gets some data, for example:
select type_of_client from table1;
type_of_client
--------------
restaurant
bar
cinema
...
And I would like to use these results into a jsonb element, for example:
select count(*) from table2 where fields->>'restaurant' is null;
select count(*) from table2 where fields->>'bar' is null;
select count(*) from table2 where fields->>'cinema' is null;
Expected results:
10
20
5
Is it possible?
I need to make it dynamically because there are a lot of type_of_clients at table_1
2
Answers
I’m not sure why one would do such a thing, but technically
does match your example.
There are a few useful row_to_json(b) functions, as well as other jsonb aggregations functions: https://www.postgresql.org/docs/current/functions-aggregate.html#id-1.5.8.27.5.2.4.12.1.1.1
Yes, you can do that, the
->
operator can take any expression of typetext
as its second operand, not just literals. You can use a subquery (if it returns 0 to 1 rows with a single column, not more):or you might be looking for a cross join:
or for your use case: