我正在使用Teradata中的SQL来研究客户及他们的购物习惯。
说我有以下信息:
Table wklytrans
CustNm GroceryStore # WklyTrxns Sum WklyTrxns CustType
Jack Publix 2 $70 Publix
Ruby Kroger 1 $15 Both
Moe Kroger 4 $120 Kroger
Ruby Publix 1 $20 Both
我想创建一个新表,按如下方式对它们进行分类:
CustNm CustType # PubTrxns Sum PubTrxns # KroTrxns Sum KroTrxns
Jack Publix 2 $70 NULL NULL
Ruby Both 1 $20 1 $15
Moe Kroger NULL NULL 4 $120
我目前正在尝试运行的代码如下:
CREATE MULTISET VOLATILE TABLE custclass AS(
SEL
CustNm,
CustType,
CASE WHEN CustType IN 'Both' AND GroceryStore IN 'Publix' THEN # WklyTrxns
WHEN CustType IN 'Publix' THEN # WklyTrxns
END AS # PubTrxns,
CASE WHEN CustType IN 'Both' AND GroceryStore IN 'Publix' THEN Sum WklyTrxns
WHEN CustType IN 'Publix' THEN Sum WklyTrxns
END AS Sum PubTrxns,
CASE WHEN CustType IN 'Both' AND GroceryStore IN 'Kroger' THEN # WklyTrxns
WHEN CustType IN 'Kroger' THEN # WklyTrxns
END AS # KroTrxns,
CASE WHEN CustType IN 'Both' AND GroceryStore IN 'Kroger' THEN Sum WklyTrxns
WHEN CustType IN 'Kroger' THEN Sum WklyTrxns
END AS Sum KroTrxns
FROM wklytrans
)
WITH DATA
PRIMARY INDEX (CustNm)
ON COMMIT PRESERVE ROWS;
这是目前输出的内容:
CustNm CustType # PubTrxns Sum PubTrxns # KroTrxns Sum KroTrxns
Jack Publix 2 $70 NULL NULL
Ruby Both 1 $20 NULL NULL
Ruby Both NULL NULL 1 $15
Moe Kroger NULL NULL 4 $120
如何让我的代码将Ruby的事务组合到同一行,以便它看起来像我想要的输出?
感谢任何帮助!
答案 0 :(得分:0)
您可能需要使用MAX / GROUP BY组合多行,如下所示:
CREATE MULTISET VOLATILE TABLE custclass AS(
SEL
CustNm,
CustType,
MAX(CASE WHEN CustType IN 'Both' AND GroceryStore IN 'Publix' THEN # WklyTrxns
WHEN CustType IN 'Publix' THEN # WklyTrxns
END) AS # PubTrxns,
MAX(CASE WHEN CustType IN 'Both' AND GroceryStore IN 'Publix' THEN Sum WklyTrxns
WHEN CustType IN 'Publix' THEN Sum WklyTrxns
END) AS Sum PubTrxns,
MAX(CASE WHEN CustType IN 'Both' AND GroceryStore IN 'Kroger' THEN # WklyTrxns
WHEN CustType IN 'Kroger' THEN # WklyTrxns
END) AS # KroTrxns,
MAX(CASE WHEN CustType IN 'Both' AND GroceryStore IN 'Kroger' THEN Sum WklyTrxns
WHEN CustType IN 'Kroger' THEN Sum WklyTrxns
END) AS Sum KroTrxns
FROM wklytrans
GROUP BY 1,2
)
WITH DATA
PRIMARY INDEX (CustNm)
ON COMMIT PRESERVE ROWS;