我有一个MS Access数据库,用于每个客户端ID的产品ID列表。
目前,该表格设置如下:
CLI_ID || PRODUCT_ID
963506 || 49001608
968286 || 49001645
987218 || 00048038
987218 || 49001401
999999 || 9999999
999999 || 9999998
999999 || 9999997
999999 || 9999996
我想将数据转置为如下所示:
CLI_ID || PRODUC1 || PRODUC2 || PRODUC3 || PRODUC4 ||
963506 || 49001608 ||
968286 || 49001645 ||
987218 || 00048038 || 49001401 ||
999999 || 99999999 || 99999998 || 99999997 || 99999996 ||
在上面的示例中,有些客户的产品数量超过了4个,因此我希望通过计算每个客户端ID中的产品ID数量来扩展查询。
我从ChrisPadgham's post获取了代码并对其进行了修改以满足我的需求......这是我到目前为止所做的,但它不会比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);
任何帮助将不胜感激!
答案 0 :(得分:3)
尝试为您的数据添加每个客户项计数器。 Examples Found Here
看起来你需要创建一个临时表,因为Access在嵌套查询时无法跟踪内部指针。
创建临时表:
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;
然后让您的数据透视表引用临时表。
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;
输出:
CLI_ID PRODUCT 1 PRODUCT 2 PRODUCT 3 PRODUCT 4 963506 49001608 968286 49001645 987218 00048038 49001401 999999 9999996 9999997 9999998 9999999
答案 1 :(得分:0)
Jeff的答案基本上是正确的,尽管不严格要求临时表:
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
返回
CLI_ID PRODUCT_1 PRODUCT_2 PRODUCT_3 PRODUCT_4
------ --------- --------- --------- ---------
963506 49001608
968286 49001645
987218 00048038 49001401
999999 9999996 9999997 9999998 9999999