Another solution would be using a
common table expression and an
OLAP function:
WITH RAW (ACCT ,PROD_NAME ,SEQ)
AS ( SELECT T1.ACCT
,T2.PROD_NAME
,ROW_NUMBER() OVER(PARTITION BY T1.ACCT
ORDER BY T1.PROD_ID)
FROM TAB1 T1
JOIN TAB2 T2
ON T2.PROD_ID = T1.PROD_ID
)
SELECT R1.ACCT
,COALESCE(R1.PROD_NAME,' ') AS FIRST
,COALESCE(R2.PROD_NAME,' ') AS SECOND
,COALESCE(R3.PROD_NAME,' ') AS THIRD
FROM RAW R1
LEFT OUTER JOIN RAW R2
ON R2.ACCT = R1.ACCT
AND R2.SEQ = 2
LEFT OUTER JOIN RAW R3
ON R3.ACCT = R1.ACCT
AND R3.SEQ = 3
WHERE R1.SEQ = 1
;
---------+---------+---------+---------+---------+--
ACCT FIRST SECOND THIRD
---------+---------+---------+---------+---------+--
1234 PRODUCT 1 PRODUCT 3
4321 PRODUCT A PRODUCT B PRODUCT C
Please note:
- Depending on the design and size of your table(s) this query might become a cost issue.
- You need to know the maximum number of projects that can be assigned to an account, and repeat the queries LEFT OUTER JOINs accordingly.
- For this example, I've added some more data to the given setup (ID=2, ACCT=4321, PROD_ID/NAME=PA, PB, PC).