I’m trying to union two tables and then create one line of information for both of then.
My code is:
with cte as (
select id,
dt_month_transaction,
dt_first_transaction,
transaction_total,
null as dt_month_redemption,
null as redemption_total
from tb_transaction
union
select id,
null as dt_month_transaction,
null as dt_first_transaction,
null as transaction_total,
dt_month_redemption,
redemption_total
from tb_redemption
)
Then, the output is:
id | dt_month_transaction | dt_first_transaction | transaction_total | dt_month_redemption | redemption_total |
---|---|---|---|---|---|
1 | 2023-04-01 | 2019-10-01 | 27.508 | ||
1 | 2022-04-01 | 108.0 | |||
2 | 2023-04-01 | 2019-10-01 | 26.308 | ||
2 | 2022-04-01 | 108.0 |
But it should be like this:
id | dt_month_transaction | dt_first_transaction | transaction_total | dt_month_redemption | redemption_total |
---|---|---|---|---|---|
1 | 2023-04-01 | 2019-10-01 | 27.508 | 2022-04-01 | 108.0 |
2 | 2023-04-01 | 2019-10-01 | 26.308 | 2022-04-01 | 108.0 |
There’s a way to perform what I’m trying to do?
3
Answers
join, not union. Then simply select the columns mix and match as desired from both tables. "INNER" join picks up only records from both tables that have matching keys.
"LEFT JOIN" picks up all records from
tb_transactions
(A) and only matching records fromtb_redemption
(B). When no matching B record,select
ed B columns will be nullAssuming id is the correlating column and you need data for those id values only which are present in both tables, you can try to use join as below
UNION
does not merge rows.Seems like you want a
FULL [OUTER] JOIN
:This preserves all rows, even if there is no match in the other table. The
USING
clause in the join condition simplifies the query. You always get anid
without the need forCOALESCE(t.id, r.id)
.