我正在尝试按月中的某天生成累计销售额(这样我就可以在同一个图表上绘制多个月的图表,在X轴上显示月份日期,在Y轴上显示累计金额总和),但是我左右加入generate_series(1,31),我得到了:
d sum
1 3746.5
2 5731.5
3 9258.42
而我想要的是:
d sum
1 3746.5
2 5731.5
3 9258.42
4 0
5 0
... 0
31 0
这是我的问题:
SELECT
d,
SUM (SUM("Amount")) OVER (ORDER BY "CloseDate" ASC)
FROM
salesforce."Opportunity"
LEFT JOIN generate_series (1, 31) d ON d = EXTRACT (DAY FROM "CloseDate")
WHERE
EXTRACT (MONTH FROM "CloseDate") = EXTRACT (MONTH FROM now())
AND EXTRACT (YEAR FROM "CloseDate") = EXTRACT (YEAR FROM now())
AND "StageName" = 'Closed Won'
AND "Type" = 'Renewal'
GROUP BY
"CloseDate",
d
我可以感觉到我做错了什么,但我不确定是什么。任何帮助将不胜感激 - 谢谢!!
答案 0 :(得分:0)
右。您需要将聚合放在子查询中,首先从generate_series中选择,然后选择左连接:
WITH days as (
select d from generate_series (1, 31) d),
aggregates as (
SELECT
EXTRACT (DAY FROM "CloseDate") d,
SUM (SUM("Amount")) OVER (ORDER BY "CloseDate" ASC) total
FROM
salesforce."Opportunity"
WHERE
EXTRACT (MONTH FROM "CloseDate") = EXTRACT (MONTH FROM now())
AND EXTRACT (YEAR FROM "CloseDate") = EXTRACT (YEAR FROM now())
AND "StageName" = 'Closed Won'
AND "Type" = 'Renewal'
GROUP BY
"CloseDate"
)
select days.d, aggregates.total
from days
left join aggregates on days.d = aggregates.d
order by days.d;
如果将group by
放在子查询中然后将该子查询连接到几天,那么这是最简单和最可读的。您还可以添加更多子查询并将它们连接起来,以便在同一个表中包含更多聚合,甚至来自不同的源表。