添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Redshift - 聚合函数调用可能没有嵌套的聚合或窗口函数

4 人关注

我试图建立一个SQL查询,以计算基于某些值的销售总额,如下所示。

下面是我的数据集的情况。

cust_name,sales_count,day_count
cust_a,100,3
cust_a,200,5
cust_a,150,7
cust_a,120,1
cust_a,180,10
cust_a,100,8
cust_b,20,3
cust_b,10,4
cust_b,50,6
cust_b,60,8
cust_b,15,9

我希望得到以下格式的输出结果

cust_name,sales_count,day_count
cust_a,280,last_14
cust_a,450,last_7
cust_b,85,last_14
cust_b,80,last_7

下面是我试图建立的案例语句

select cust_name, 
       sum(case when day_count > 7 then count(sales_count) else 0 end) as count_14,
       sum(case when day_count < 7 then count(sales_count) else 0 end) as count_7
from sales
group by cust_name;

我使用的是Amazon Redshift数据库。

在这个链接中发现了一个类似的问题(Amazon Redshift - Get week wise sales count by category),但我一直得到聚合函数调用可能没有嵌套聚合或窗口函数

谁能帮助解决这个问题。谢谢。

2 个评论
你的样本数据中的 pendo_visitor_id 列在哪里?
对不起,我的意思是 "sales_count"。是我的错字。我已经编辑了原始信息
sql
aggregate-functions
amazon-redshift
Kevin Nash
Kevin Nash
发布于 2018-06-19
2 个回答
D-Shih
D-Shih
发布于 2018-06-19
已采纳
0 人赞同

根据你的问题,你可以试试这个查询。

使用 SUM CASE WHEN Expression。

select cust_name, 
       sum(case when day_count > 7 then sales_count else 0 end) as count_14,
       sum(case when day_count < 7  then sales_count else 0 end) as count_7
from sales
group by cust_name;

因为Aggregate functions ,不能多次嵌套。

如果你想修复

sum(case when day_count > 7 then count(sales_count) else 0 end) 

你可以尝试写一个子查询来解决这个问题。

SELECT cust_name,
       sum(case when day_count > 7 then cnt else 0 end) as count_14,
       sum(case when day_count < 7 then cnt else 0 end) as count_7
FROM (
    SELECT cust_name,(case when day_count > 7 then 1
                           when day_count < 7 then 2
                           else null
                      end) grp,
          count(sales_count) cnt
    FROM sales
    GROUP BY cust_name,
             (case when day_count > 7 then 1
                   when day_count < 7 then 2
                   else null
             end)
WHERE grp is not null
GROUP BY cust_name
    
谢谢你的回答。因为我想得到count(sales_count),当我用count(sales_count)改变case语句时,我得到一个错误 "聚合函数调用可能没有嵌套聚合或窗口函数"。能否请您协助。
聚合函数不能多次嵌套,所以你可以尝试写一个子查询来解决这个问题。你可以看看我编辑的答案:) @KevinNash
AlexYes
AlexYes
发布于 2018-06-19
0 人赞同

来产生所需的输出,你所需要的仅仅是

sum(case when day_count > 7 then sales_count else 0 end)

你在括号里的是表达式,你把它的输出重定向到汇总它的sum函数,所以对于 cust_a ,它产生以下一组值。

cust_a,100,3 -> 0 (3<=7)
cust_a,200,5 -> 0 (5<=7)
cust_a,150,7 -> 0 (7<=7)
cust_a,120,1 -> 0 (1<=7)