我正在尝试在Amazon Redshift中进行计数(案例(。
使用这个参考,我写道:
select
sfdc_account_key,
record_type_name,
vplus_stage,
vplus_stage_entered_date,
site_delivered_date,
case when vplus_stage = 'Lost' then -1 else 0 end as stage_lost_yn,
case when vplus_stage = 'Lost' then 2000 else 0 end as stage_lost_revenue,
case when vplus_stage = 'Lost' then datediff(month,vplus_stage_entered_date,CURRENT_DATE) else 0 end as stage_lost_months_since,
count(case when vplus_stage = 'Lost' then 1 else 0 end) as stage_lost_count
from shared.vplus_enrollment_dim
where record_type_name = 'APM Website';
但是我收到此错误:
[42803][500310] [Amazon](500310) Invalid operation: column "vplus_enrollment_dim.sfdc_account_key" must appear in the GROUP BY clause or be used in an aggregate function; java.lang.RuntimeException: com.amazon.support.exceptions.ErrorException: [Amazon](500310) Invalid operation: column "vplus_enrollment_dim.sfdc_account_key" must appear in the GROUP BY clause or be used in an aggregate function;
在我添加计数之前,查询运行良好。我不确定我在这里做错了什么 - 谢谢!
如果没有group by
,就不能有一个聚合函数(总和、计数等(
语法是这样的
select a, count(*)
from table
group by a (or group by 1 in Redshift)
在查询中,您需要添加
group by 1,2,3,4,5,6,7,8
因为您有 8 列,而不是 count
由于我不知道您的数据和用例,我不能告诉您它会给您正确的结果,但SQL在语法上是正确的。
基本规则是:
- 如果您使用的是聚合函数(例如
COUNT(...)
(,则必须提供一个GROUP BY
子句来定义分组 - 例外:如果所有列都是聚合(例如
SELECT COUNT(*), AVG(sales) FROM table
( - 任何不是聚合函数的列都必须出现在
GROUP BY
中(例如SELECT year, month, AVG(sales) FROM table GROUP BY year, month
(
您的查询有一个COUNT()
聚合函数与非聚合值混合在一起,这会导致错误。
在查看查询时,您可能不希望对所有列进行分组(例如stage_lost_revenue
和stage_lost_months_since
看起来不像对列进行分组(。您可能希望模拟查询结果,以确定您实际希望从此类查询中获得什么。