BigQuery RANK()在Having或Where子句中

时间:2014-04-25 14:43:02

标签: java sql google-app-engine google-bigquery

在BigQuery中,我有一个查询,它使用RANK()函数按来源的总计数对用户进行分组。我只关心前10名用户。目前,我在子选择中执行RANK()函数,WHERE子句存在于父查询中以限制结果。有人可以向我解释如何在没有父查询的情况下完成此操作吗?我想要运行的查询如下所示:

SELECT source, user, count( tweet_id ) as total, max( friends ) as friends, 
RANK() OVER (PARTITION BY source ORDER BY total DESC, friends DESC ) as user_rank
FROM tweets
GROUP BY source, user
HAVING user_rank <= 10

但我收到错误:表'推文'中找不到字段'user_rank'。我可以ORDER BY使用user_rank,而不是过滤。

感谢您的任何建议!

1 个答案:

答案 0 :(得分:4)

您可能需要执行类似

的操作
SELECT source, user, total, friends, user_rank

FROM (
    SELECT source, user, count( tweet_id ) as total, max( friends ) as friends, 
    RANK() OVER (PARTITION BY source ORDER BY total DESC, friends DESC ) as user_rank
    FROM tweets
    GROUP BY source, user
) 

HAVING user_rank <= 10