I have a table called main_table
and it has the following records
cust_id | start_date | end_date |
---|---|---|
10001 | 2022-12-01 | 2022-12-30 |
10001 | 2023-01-03 | 2023-02-01 |
I have another table called penalty_a_type
and it has the following records
cust_id | start_date | end_date | penalty_a |
---|---|---|---|
10001 | 2022-12-01 | 2022-12-30 | 0 |
10001 | 2023-01-03 | 2023-02-01 | 0 |
I have another table called penalty_b_type
and it has the following records
cust_id | start_date | end_date | penalty_b |
---|---|---|---|
10001 | 2022-12-01 | 2022-12-30 | 0 |
10001 | 2023-01-03 | 2023-02-01 | 4 |
I want to join these tables so that it looks like
cust_id | start_date | end_date | penalty_a | penalty_b |
---|---|---|---|---|
10001 | 2022-12-01 | 2022-12-30 | 0 | 0 |
10001 | 2023-01-03 | 2023-02-01 | 0 | 4 |
But I am getting the following table
cust_id | start_date | end_date | penalty_a | penalty_b |
---|---|---|---|---|
10001 | 2022-12-01 | 2022-12-30 | 0 | 0 |
10001 | 2022-12-01 | 2022-12-30 | 0 | 4 |
10001 | 2023-01-03 | 2023-02-01 | 0 | 0 |
10001 | 2023-01-03 | 2023-02-01 | 0 | 4 |
The code I have tried is
SELECT m.cust_id,
m.start_date,
m.end_date,
pa.penalty_a
pb.penalty_b
FROM main_table m
JOIN penalty_a_type pa
ON m.cust_id = pa.cust_id
JOIN penalty_b_type pb
ON m.cust_id = pb.cust_id
GROUP BY m.cust_id, m.start_date, m.end_date, pa.penalty_a, pb.penalty_b
3
Answers
cust_id
on main table is duplicated.If you care about the different start/end dates, then the result is fine. If you don’t care, then remove it from group (and select)
You can try with ROW_NUMBER and the following result as
https://dbfiddle.uk/cvg7jiRu