Scenario :
Input table 1 : need to compare the value of field2 of table1 with field 3 of table 2
example :
select from svc_lz.fn_abc;svc_lz.fn_cde; so field 2 values of table 1 is
present after ‘select’ i.e svc_lz.fn_abc and svc_lz.fn_cde so we need to
join with field 3 of table 2 example : svc_lz.fn_abc and svc_lz.fn_cde.If there is join
then fetch field 4 assigned to table 2 and place it in output table field 3.
Input table 1:
field1 | field2 |
---|---|
a | select from svc_lz.fn_abc;svc_lz.fn_cde; |
b | select *From mfg_lz.fn_test,mfg_a.fn_test1 |
c | select *From mfg_j.fn_test2 |
d | select *From mfg_j.fn_test3;mfg_j.fn_test4; |
Input table 2 :
field3 | field4 |
---|---|
svc_lz.fn_abc | {test} |
svc_lz.fn_cde | {test1,test2} |
mfg_lz.fn_test | {test3} |
mfg_j.fn_test4 | {test5} |
Output:
field1 | field2 | field3 |
---|---|---|
a | select from svc_lz.fn_abc;svc_lz.fn_cde; | test,test1,test2 |
b | select *From mfg_lz.fn_test,mfg_a.fn_test1 | test3 |
c | select *From mfg_j.fn_test2 | NULL |
d | select *From mfg_j.fn_test3;mfg_j.fn_test4; | test5 |
I have search and check need to do string_split and perform inner join between field 2 from tbl1 and
field3 from tbl2 but I am not sure how to start with,I have tried using cte
functionality but I am new to sql so struggling to find the starting point for this.If
anyone can help pls.
2
Answers
For solving your problem in PostgreSQL, where you need to compare data between two tables based on fields extracted from strings and then populate a target table, you can follow a step-by-step approach using PostgreSQL-specific functions.
Steps to Solve the Problem
field2
oftable1
: Use theregexp_split_to_table
function to splitfield2
on specific delimiters and prepare it for joining.table2
on these split values to find corresponding entries.string_agg
to concatenate all matchingfield4
values.SQL Query Explanation
Step 1: Split
field2
and Prepare for JoinHere’s how you can create a Common Table Expression (CTE) to handle the splitting:
This CTE splits
field2
on commas and semicolons and creates a new row for each part usingunnest
.Step 2: Join and Aggregate
Now, use the CTE to join with
table2
and aggregate the results:Step 3: Insert into Target Table
Assuming you have a target table with columns
field1
,field2
, andfield3
, you can insert the results as follows:Additional Notes
regexp_split_to_array
accurately captures the delimiters you expect infield2
.string_agg
is used to concatenate values fromfield4
associated with each match, separated by commas.This approach will effectively allow you to compare and aggregate data from two PostgreSQL tables and populate a target table based on your criteria.
For more postgres/yugabyte exciting posts visit: https://www.developerscoffee.com
See example
Result is
First part is
This subquery output is
Next step JOIN table1 and expanded table2 (previous subquery)
Output is
Demo