Question

I have an MS Access database for product ID list for each client ID.

Currently, the table is set up as the following:

CLI_ID || PRODUCT_ID
963506 || 49001608
968286 || 49001645
987218 || 00048038
987218 || 49001401
999999 || 9999999    
999999 || 9999998
999999 || 9999997
999999 || 9999996

I would like to transpose the data to look like this:

CLI_ID || PRODUC1  || PRODUC2  || PRODUC3  || PRODUC4  ||
963506 || 49001608 ||
968286 || 49001645 ||
987218 || 00048038 || 49001401 ||
999999 || 99999999 || 99999998 || 99999997 || 99999996 ||

There are clients with more products than 4 in the example shown above so I would like the query to be expandable by counting # of product IDs in each client ID.

I took the code from ChrisPadgham's post and modified it to meet my needs...Here is what I have so far but it is not going further than PRODUC1:

TRANSFORM Last([PRODUCT_ID]) AS Details
SELECT Source_Table.CLI_ID
FROM Source_Table
GROUP BY Source_Table.CLI_ID
PIVOT "PRODUC" & (DCount("[PRODUCT_ID]","[Source_Table]", "[PRODUCT_ID]<>" & 
[PRODUCT_ID] & " AND [CLI_ID]=" & [CLI_ID]) +1);

Any help would be appreciated!

Was it helpful?

Solution 2

Jeff's answer is essentially correct in its approach, although a temporary table is not strictly required:

TRANSFORM First(PRODUCT_ID) AS whatever
SELECT CLI_ID
FROM
    (
        SELECT t1.CLI_ID, t1.PRODUCT_ID, 'PRODUCT_' & COUNT(*) AS XtabColumn
        FROM 
            Source_Table AS t1
            INNER JOIN
            Source_Table AS t2
                ON t1.CLI_ID = t2.CLI_ID
                    AND t1.PRODUCT_ID >= t2.PRODUCT_ID
        GROUP BY t1.CLI_ID, t1.PRODUCT_ID
    )
GROUP BY CLI_ID
PIVOT XtabColumn

returns

CLI_ID  PRODUCT_1  PRODUCT_2  PRODUCT_3  PRODUCT_4
------  ---------  ---------  ---------  ---------
963506  49001608                                  
968286  49001645                                  
987218  00048038   49001401                       
999999  9999996    9999997    9999998    9999999  

OTHER TIPS

Try adding a per client item counter to your data. Examples Found Here

It looks like your going to need to create a temp table as Access can't keep track of internal pointers when nesting the queries.

Create a temp table:

SELECT t1.CLI_ID, t1.PRODUCT_ID, (SELECT COUNT(*) 
FROM Source_Table t2 
WHERE t2.CLI_ID = t1.CLI_ID 
AND t2.PRODUCT_ID <= t1.PRODUCT_ID 
) AS PROD_COUNT INTO TEMP_CLI_PROD
FROM Source_Table AS t1
GROUP BY t1.CLI_ID, t1.PRODUCT_ID;

Then have your pivot table reference the temp table.

TRANSFORM Last(TEMP_CLI_PROD.PRODUCT_ID) AS LastOfPRODUCT_ID
SELECT TEMP_CLI_PROD.CLI_ID
FROM TEMP_CLI_PROD
GROUP BY TEMP_CLI_PROD.CLI_ID
PIVOT "PRODUCT " & TEMP_CLI_PROD.PROD_COUNT;

Output:

CLI_ID  PRODUCT 1     PRODUCT 2     PRODUCT 3     PRODUCT 4
963506  49001608
968286  49001645
987218  00048038      49001401
999999  9999996       9999997       9999998       9999999
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top