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

时间:2018-06-19 08:28:39

标签: sql aggregate-functions amazon-redshift

我正在尝试构建一个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 个答案:

答案 0 :(得分:3)

根据您的问题,您可以尝试此查询。

使用SUMCASE WHEN表达式。

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;

修改

Becasue 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)
)t 
WHERE grp is not null
GROUP BY cust_name

答案 1 :(得分:1)

产生所需的输出,你需要的只是

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)
cust_a,180,10 -> 180 (10>7)
cust_a,100,8 -> 100 (8>7)

然后总和为280