I have two tables. One is a Reference
table, used to sort priority, and one is a Customer
table. The Reference
table is used to give priority to each column in the Customer
table, to give a different order for the individual columns for a single customer.
Reference Table:
---------------------------------------
| Priority | Attribute | sourceID |
---------------------------------------
| 1 | EMAIL | 1 |
| 2 | EMAIL | 2 |
| 3 | EMAIL | 3 |
| 2 | NAME | 1 |
| 1 | NAME | 2 |
| 3 | NAME | 3 |
---------------------------------------
Customer table:
-----------------------------------------------------------------------
| CustomerID | Name | Email | SourceID | Date |
-----------------------------------------------------------------------
| 1 | John | NULL | 1 | 03/01/2017 |
| 1 | NULL | [email protected] | 3 | 01/01/2017 |
| 1 | J | [email protected] | 2 | 02/01/2017 |
-----------------------------------------------------------------------
Result:
---------------------------------------------
| CustomerID | Name | Email |
---------------------------------------------
| 1 | John | [email protected] |
---------------------------------------------
At the moment I'm using the following query to do this:
SELECT DISTINCT
FIRST_VALUE(c.Name IGNORE NULLS)
OVER (PARTITION BY p.customerID
ORDER BY r.PRIORITY, c.DATE
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS EMAIL,
FIRST_VALUE(c.Email IGNORE NULLS)
OVER (PARTITION BY c.customerID
ORDER BY r.PRIORITY, c.DATE
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS EMAIL
FROM Customer c
JOIN reference r ON c.sourceID = r.sourceID;
However, this does take the different attributes for each column into consideration. I need to add a filter of some sort to each of the partitions by parts.
Can anyone assist with how I can go about doing this?