如何计算用户运行的命令数?

时间:2016-07-12 19:18:48

标签: sql hive hiveql

我有一张看起来像这样的表

user_id   ...
1         ...
1         ...
2         ...

我想要一张看起来像这样的表

user_id   num_commands   ...
1         2              ...
2         1              ...

我正在使用查询

select
user_id as id,
count(user_id) as num_commands,
...
from table_name
group by user_id

但它返回错误FAILED: SemanticException [Error 10025]: Line 4:0 Expression not in GROUP BY key 'num_commands'。这对我来说似乎毫无意义;我意识到num_commands不在GROUP BY语句中,但它是聚合函数的结果,所以它为什么重要?

1 个答案:

答案 0 :(得分:1)

这是错误的

select
 user_id as id,
 count(user_id) as num_commands
 from table_name
 group by user_id

count(user_id)和group by user_id引发异常

select
 user_id as id,
 count(user_id) as num_commands,
 other_column1, 
 other_column2 
 from table_name
 group by user_id

这是错误的,因为不是

组中的列

这是对的

select
 user_id as id,
 count(*) as num_commands,
 other_column1, 
 other_column2 
 from table_name
 group by user_id, other_column1,      other_column2 


select
 user_id as id,
 count(*) as num_commands,
 sum(other_column1), 
 avg(other_column2) 
 from table_name
 group by user_id