The database I'm working in is Snowflake. I also have to work through an interface and can't edit the SQL query directly. I'm trying to add a JOIN to a FROM clause that is connecting two schemas with 1 key that is shared between the two tables.
The goal is to get all of the information I am selecting to show in one row, the issue is that my query is causing the table to display up to four rows for the same personID.
DW.DTBL_PERSON
| Person_Key | Person_ID | Person_Name |
|---|---|---|
| 1 | 4500 | Person A |
| 2 | 4501 | Person B |
| 3 | 4502 | Person C |
REPORTING.MTBL_CONTACTS
| Person_Key | Contact_Priority_Order | Contact_First_Name |
|---|---|---|
| 1 | 1 | Anna |
| 1 | 2 | Steve |
| 2 | 1 | Joseph |
| 3 | 1 | Mimi |
| 3 | 2 | Mitchell |
| 3 | 3 | Chris |
SELECT DISTINCT
dtbl_person.person_key as "KEY",
dtbl_person.person_name as "Person Name",
CASE
WHEN T2.CONTACT_PRIORITY_ORDER = 1 THEN T2.CONTACT_FIRST_NAME as "First Contact First Name"
END,
CASE
WHEN T2.CONTACT_PRIORITY_ORDER = 2 THEN T2.CONTACT_FIRST_NAME as "Second Contact First Name"
END,
CASE
WHEN T2.CONTACT_PRIORITY_ORDER = 3 THEN T2.CONTACT_FIRST_NAME as "Third Contact First Name"
END
FROM
DW.DTBL_PERSON
INNER JOIN
REPORTING.MTBL_CONTACTS AS T1 ON DTBL_PERSON.PERSON_KEY = T1.PERSON_KEY
INNER JOIN
REPORTING.MTBL_CONTACTS AS T2 ON CONCAT(T2.PERSON_KEY, T2.CONTACT_PRIORITY_ORDER) = CONCAT(T1.PERSON_KEY, T1.CONTACT_PRIORITY_ORDER)
ORDER BY
dtbl_students.person_id
What it's doing
| KEY | Person Name | First Contact First Name | Second Contact First Name | Third Contact First Name |
|---|---|---|---|---|
| 1 | Person A | Steve | ||
| 1 | Person A | Anna | ||
| 2 | Person B | Joseph | ||
| 3 | Person C | Chris | ||
| 3 | Person C | Mimi | ||
| 3 | Person C | Mitchell |
What I want it to do
| KEY | Person Name | First Contact First Name | Second Contact First Name | Third Contact First Name |
|---|---|---|---|---|
| 1 | Person A | Anna | Steve | |
| 2 | Person B | Joseph | ||
| 3 | Person C | Mimi | Mitchell | Chris |
Right now it's pulling all the information, just creating new rows to display the information. I want it to show all of the information in the same row for the same key. The second INNER JOIN is supposed to act as a self join which I was hoping to use to resolve the issue of displaying multiple rows instead of displaying the information for each key in one row.
Any help on this issue would be much appreciated.
MAX,MINor evenFIRST_VALUEor similar functions does not really matter in your case. You will just "collapse" the separate rows into one per group by aggregating.