给定时间内的 Postgres SUM
Posted
技术标签:
【中文标题】给定时间内的 Postgres SUM【英文标题】:Postgres SUM over given time 【发布时间】:2021-03-02 01:02:27 【问题描述】:我正在尝试使用 Postgres 在给定时间内对谷歌分析数据求和。我不太确定如何解决分组问题。您在下面看到的查询每天返回一列。我想总结给定日期的所有点击次数。因此,查询应该为每个广告系列返回 1 行,每行有一列表示点击的总和。
SELECT
sa.id AS salesforce_account_id,
acp.campaignid,
acp.campaignname,
date,
SUM(clicks) as clicks
FROM
adwords_campaign_performance acp
INNER JOIN salesforce_account sa ON
sa.adwords_id = acp.adwords_customerid
WHERE acp.date >= '2020-10-01'
AND acp.date <= '2020-10-03'
GROUP BY sa.id, acp.campaignid, acp.campaignname, date
我可以编写查询,使其返回整个月份的数字,如下所示:
SELECT
sa.id AS salesforce_account_id,
acp.campaignid,
acp.campaignname,
date_trunc('month', date) AS MONTH,
SUM(clicks) as clicks
FROM
adwords_campaign_performance acp
INNER JOIN salesforce_account sa ON
sa.adwords_id = acp.adwords_customerid
WHERE MONTH = '2020-10-01 00:00:00'
AND sa.id = 3148
GROUP BY sa.id, acp.campaignid, acp.campaignname, MONTH
任何帮助将不胜感激。谢谢!
【问题讨论】:
【参考方案1】:我认为您希望 generate_series()
生成该月的所有日期:
SELECT gs.date, sa.id AS salesforce_account_id, acp.campaignid, acp.campaignname,
SUM(clicks) as clicks
FROM generate_series('2020-10-01'::date, '2020-10-31'::date, interval '1 day') gs(dte) LEFT JOIN
adwords_campaign_performance acp
ON acp.date >= gs.dte AND
acp.date < gs.dte + INTERVAL '1 DAY' LEFT JOIN
salesforce_account sa
ON sa.adwords_id = acp.adwords_customerid
GROUP BY gs.dte, sa.id, acp.campaignid, acp.campaignname, date
【讨论】:
【参考方案2】:您在下面看到的查询每天返回一列。我想总结给定日期的所有点击次数。因此,查询应该为每个广告系列返回 1 行,每行有一列表示点击的总和。
所以只需从select
和group by
子句中删除date
:
SELECT
sa.id AS salesforce_account_id,
acp.campaignid,
acp.campaignname,
SUM(clicks) as clicks
FROM adwords_campaign_performance acp
INNER JOIN salesforce_account sa ON sa.adwords_id = acp.adwords_customerid
WHERE acp.date >= '2020-10-01'
AND acp.date <= '2020-10-03'
GROUP BY sa.id, acp.campaignid, acp.campaignname
【讨论】:
以上是关于给定时间内的 Postgres SUM的主要内容,如果未能解决你的问题,请参考以下文章
Django 仅使用 Sqlite 按距离过滤(无 GeoDjango、PostGres、MySQL、GIS)
如何查询postgres数据库以获取某些坐标10公里半径内的所有点
相同数据空间内的 postgres 主要升级(9.5.x 到 9.6.x)