I have tables like so
regist table
| userID | registDate |
|---|---|
| 1 | 2022-01-22 |
| 2 | 2022-01-23 |
session tables
| userID | date_key | traffic |
|---|---|---|
| null | 2022-01-02 | |
| 1 | 2021-01-03 | |
| 1 | 2021-01-04 | |
| 1 | 2021-01-05 | |
| 2 | 2021-01-15 | |
| 2 | 2021-01-25 | |
| 3 | 2021-01-20 |
output
| userID | date_key | traffic | regist date |
|---|---|---|---|
| 1 | 2021-01-03 | 2022-01-22 | |
| 1 | 2021-01-04 | 2022-01-22 | |
| 1 | 2021-01-05 | 2022-01-22 | |
| 2 | 2021-01-15 | 2022-01-23 |
How do I merge the tables so that I can return the regist date. Do I do a right join?
Is this correct?
select * from
sessiontables st
left join registtable rt
on st.userID=rt.userID
where st.userID is not null
how to do exist userID exist in regist table statement ?
>Solution :
if I understand correctly, You can try to use self join with an aggregate function.
select rt.userID,
st.date_key,
st.traffic,
rt.registDate
from (
SELECT userID,min(date_key) date_key,traffic
FROM sessiontables
GROUP BY traffic,userID
) st
JOIN registtable rt
ON st.userID=rt.userID