SQL 计数和选择其他字段

SQL Count and selecting other fields

我知道的很基础,但让自己感到困惑。我只想在末尾添加一列,显示 unique_key

的计数
select unique_key , date_trunc('month',enrollment_date::date) date_enrolled,
enrollment_reason, count(unique_key)
from table1
group by unique_key;

我收到这个错误:

SQL compilation error: error line 1 at position 42 'unique_key' in select clause is neither an aggregate nor in the group by clause.

我想你打算:

select date_trunc('month',enrollment_date::date) as date_enrolled,
       enrollment_reason, count(*)
from table1
group by date_trunc('month',enrollment_date::date), enrollment_reason;

当我 运行 时,我收到错误 ...'enrollment_date' in select clause is neither an aggregate... 奇怪的是它在 unique_key 上出错。

但我认为发生的情况是您试图在 select 中显示日期和注册原因,但您没有按这些进行分组。例如,您的查询试图获取一个 unique_key 的所有行,但随后它不知道 enrollment_reason 到 return 是哪个。即使具有特定 unique_key 的每条记录都具有相同的 enrollment_reason,查询优化器也不知道这一点,因此它不会做出该假设。

通常,要解决此问题,您应该按 select 子句中不是聚合的所有内容进行分组。

select unique_key , date_trunc('month',enrollment_date::date) date_enrolled, 
enrollment_reason, count(unique_key)
from table1
group by unique_key, date_enrolled, enrollment_reason;

另一种方法是将这些属性放在一个集合中。如果您知道该列始终相同,或者您不关心从该列获得的结果,则此方法很有效。 Max 是一个常见的选择。

select unique_key,
  max(date_trunc('month',enrollment_date::date)) date_enrolled, 
  max(enrollment_reason),
  count(unique_key)
from table1
group by unique_key, date_enrolled, enrollment_reason;

您可以使用派生的 table 来实现这一点。您需要为 GROUP BY 子句提供聚合函数。

select unique_key, count(date_enrolled)
from
(select unique_key , date_trunc('month',enrollment_date::date) date_enrolled,
enrollment_reason
from table1) as t
group by unique_key;