Count(Distinct x) 和 Group By y

Count(Distinct x) and Group By y

我有包含日期​​和时间的条目。我希望结果按小时 (00, 01, 02) 分组,这很有效,但是当我想获得不同的用户数时,出现错误。

Select Substr(time, 0, 2) as Hour,
 Count(date) as Hits,
 Count(Distinct ip) as Users,
 Count(Distinct X-Forwarded-For) as ForwardedUsers
From table 
Group By Hour

编辑: 我正在使用 Microsoft 的 LogParser,我可以按原样使用 Group By HourX-Forwarded-For 也没有问题。 问题是我如何在

组中使用 Count(Distinct ip)

大多数数据库引擎不允许您按别名分组。改变这个:

Group by Hour

对此:

Substr(time, 0, 2)

很遗憾,LogParser 不支持 DISTINCT 聚合函数和 GROUP BY。从上面查询得到的错误消息中应该可以清楚地看到这一点:

Error: Semantic Error: aggregate functions with DISTINCT arguments are not supported with GROUP BY clauses

您可以做的一个技巧是完全删除 GROUP BY 子句并改为计算 COUNT DISTINCT(hourlyIp),其中 hourlyIp 是一个将小时与 IP 地址连接起来的字符串。然后,在处理结果时,您必须将 hourlyIp 字段分解回其组件。