Skip to content
Advertisement

DB2 SQL Return One Row from Left Joined Table Based on Custom Weighting

I have two tables, ‘INVOICES’ contains invoice information and ‘CSEML’ contains customer email addresses. The email address type (field EMLTP) could be designated as ‘AP’ (Accounts Payable), ‘PO’ (Purchasing), or blank (default). Each customer could have 3 email addresses in CSEML (one for each designation). I’d like to be able to do this within the query: join the invoice table to the email table and pull a maximum of one email address per invoice – the AP address if it is defined, otherwise the PO address if it is defined, otherwise the default address if defined, otherwise null.

CSEML is structured like this

Right now I have the following query

Which returns something like this when there are all 3 addresses defined:

How can I assign a weight to the different email ‘types’ so that I’m only getting the most preferred address available?

Working Code based on accepted answer

Advertisement

Answer

You may try using ROW_NUMBER here with a CASE expression to order/prioritize the email addresses of each invoice:

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement