2017-05-09 93 views
2

我試圖運行下面的查詢。目標是獲得每user_key總活動數,但因爲user_key有一個複雜的結構,我只需要'|'之後的部分。符號我不得不使用子字符串函數。然而,當我試圖運行查詢,我得到的 錯誤:SUM和GROUP BY Splice中的子串(NoSql)

SQL Error [42Y36]: Column reference 'USER_KEY' is invalid, or is part of an invalid expression. For a SELECT list with a GROUP BY, the columns and expressions being selected may only contain valid grouping expressions and valid aggregate expressions. 

的子功能的工作原理確定此查詢之外。有關此問題的任何解決方法?使用熔接機(的NoSql)

SELECT 
    substr(user_key, instr(user_key,'|') + 1) AS new_user_key, 
    SUM(
     CAST(
      activity_count AS INTEGER 
     ) 
    ) AS Total 
FROM 
    schema_name.table_name 
GROUP BY 
substr(user_key, instr(user_key,'|') + 1) 

回答

0

你GROUP BY列需要相匹配的SELECT

SELECT 
    substr(user_key, instr(user_key,'|') + 1) AS new_user_key, 
    SUM(
     CAST(
      activity_count AS INTEGER 
     ) 
    ) AS Total 
FROM 
    schema_name.table_name 
GROUP BY 
    substr(user_key, instr(user_key,'|') + 1) AS new_user_key 
+0

這沒有奏效。不允許向GROUP BY表達式添加別名。 – DorinD

0

,我發現自己的答案。我用一個表子查詢:

SELECT new_table.new_user_key, sum(new_table.total) 
from 
    (
    SELECT 
     substr(user_key, instr(user_key,'|') + 1) AS new_user_key, 
     CAST(activity_count AS INTEGER) AS Total 
    FROM schema_name.table_name 
    ) 
    as new_table 
GROUP BY 
new_table.new_user_key 

但願有人會發現這篇文章有用,將一段時間內保存到他或她。