2016-06-26 64 views
1

我正在Teradata中使用SQL研究客戶及其購物習慣。使用案例何時對Teradata中的客戶進行分類

說我有以下信息:

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

你可能需要使用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; 
+0

,完美的工作!非常感謝。 –

相關問題