亚马逊Redshift - 按类别获得周销售额

时间:2018-06-14 08:31:03

标签: sql group-by amazon-redshift

我有每日销售数据如下。我试图按销售周分组。

我尝试使用group by给出了句点的总计数,我如何修改查询以获得输出,如下所示:

预期输出:

Last N days,Count,Category

Last 7 days,225,Category_1
Last 14 days,136,Category_2
Last 7 days,172,Category_1
Last 14 days,321,Category_2

输入数据:

Date,*Sales*,Category

01-06-2018,10,Category_1
01-06-2018,19,Category_1
03-06-2018,3,Category_1
04-06-2018,13,Category_1
05-06-2018,10,Category_1
06-06-2018,14,Category_1
07-06-2018,20,Category_1
08-06-2018,49,Category_1
09-06-2018,5,Category_1
10-06-2018,4,Category_1 
11-06-2018,20,Category_1
12-06-2018,49,Category_1
13-06-2018,5,Category_1
14-06-2018,4,Category_1
01-06-2018,10,Category_1
01-06-2018,34,Category_2
03-06-2018,22,Category_2
04-06-2018,13,Category_2
05-06-2018,1,Category_2
06-06-2018,9,Category_2
07-06-2018,60,Category_2
08-06-2018,9,Category_2
09-06-2018,35,Category_2
10-06-2018,41,Category_2 
11-06-2018,2,Category_2
12-06-2018,9,Category_2
13-06-2018,35,Category_2
14-06-2018,41,Category_2

查询已尝试:

select count(*),Category from sales
group by Category;

我正在使用亚马逊红移数据库。

任何人都可以帮忙,谢谢......

自06/19更新:

select Category,
sum(case when date >= dateadd(day, -7, CURRENT_DATE) then count(sales) else 0 end) as count_07,
sum(case when date >= dateadd(day, -14, CURRENT_DATE) then count(sales) else 0 end) as count_14
from sales
group by Category

2 个答案:

答案 0 :(得分:1)

我会将值放在不同的列中。像这样:

select category, 
       sum(case when date >= dateadd(day, -7, CURRENT_DATE) then sales else 0 end) as count_07,
       sum(case when date >= dateadd(day, -14, CURRENT_DATE) then sales else 0 end) as count_14
from sales s
group by category;

答案 1 :(得分:0)

看起来你距离解决方案只有available on illumos

七天,应该如下:

Select Count(*),Category From sales Where Date >= Dateadd(day,-7, CURRENT_DATE)

按类别分组;

-7更改为-14以获得最近14天。