如何按日期汇总数据组?

时间:2020-03-03 15:15:12

标签: sql amazon-web-services amazon-athena

我有这样的查询:

SELECT id, site, clicks, approved, year, month, day
FROM df

id 点击是整数; 站点,年,月,日是字符串;并且 approved 是布尔值。

现在,我想查看每个月/每年的点击次数。为此,我想通过将年份和月份分组来汇总点击次数。

该怎么做?

2 个答案:

答案 0 :(得分:1)

尝试使用GROUP BY

SELECT year, month, SUM(clicks) AS total
FROM df
GROUP BY year, month;

旁注:我不知道表名df是数据帧的缩写,还是在这里使用R或Python。但是,在纯SQL中,希望仅维护一个日期列,而不是将年,月和日存储为单独的组件。

答案 1 :(得分:1)

也许concat()函数就是重点。

select x.*
into #df
from
(
SELECT 1 as id, 'a' as site, 23 as clicks, 1 as approved, '2020' as year, '1' as    month, '1' as day
UNION ALL
SELECT 2 as id, 'a' as site, 1 as clicks, 1 as approved, '2020' as year, '1' as month,     '1' as day
UNION ALL
SELECT 3 as id, 'a' as site, 3 as clicks, 1 as approved, '2020' as year, '3' as month,     '1' as day
UNION ALL
SELECT 4 as id, 'a' as site, 11 as clicks, 1 as approved, '2020' as year, '4' as     month, '1' as day
UNION ALL
SELECT 5 as id, 'a' as site, 345 as clicks, 1 as approved, '2020' as year, '5' as     month, '1' as day
UNION ALL
SELECT 6 as id, 'a' as site, 88 as clicks, 1 as approved, '2020' as year, '6' as     month, '1' as day
UNION ALL
SELECT 7 as id, 'a' as site, 1 as clicks, 1 as approved, '2020' as year, '12' as     month, '1' as day
) x;

select 
    concat(year, '_', month) yyyy_mm
    , sum(clicks) clicks_total
from #df
group by 
    concat(year, '_', month)

enter image description here