gpt4 book ai didi

sql - 需要帮助为没有订单的月份生成 NULL 条目

转载 作者:行者123 更新时间:2023-12-04 04:05:17 27 4
gpt4 key购买 nike

我必须创建显示表 (Tbl) 中所有字段的输出,并创建一个额外的列来按月计算每个客户的累计总和(例如,如果客户在 4 月份有两次销售,新列将具有这些销售额和两行中任何先前销售额的总和)。我能做的就这么多。

我的问题是每月为每个客户生成行即使他们没有销售,并且累积列仍然正确显示上个月的累积总和。

期望的输出: Picture Link

Customer_ID Order_ID    Order_Date  Order_Amt_Total_USD Month_ID    Cum_Total_By_Month
John 123 4/4/2019 30 Jun-19 120
John 124 4/12/2019 90 Jun-19 120
Mark null null null Jun-19 0
Sally 150 4/20/2019 50 Jun-19 50
John null null null Jul-19 120
Mark 165 7/7/2019 80 Jul-19 170
Mark 166 7/7/2019 90 Jul-19 170
Sally 160 7/5/2019 75 Jul-19 125
John null null null Aug-19 120
Mark null null null Aug-19 170
Sally null null null Aug-19 125

我将在下面列出代码,但这是一个指向 SQL fiddle 的链接,其中包含示例数据和我正在处理的部分的两个查询(在本网站上的好人的帮助下)。 http://sqlfiddle.com/#!15/1d86b/11

我可以使用第一个查询按客户和月份生成所需的累计运行总和。

我还可以生成一个基表,在第二个查询中为每个客户每个月提供一个 month_id。

我需要帮助将这两者结合起来,以便在几个月/客户没有任何销售时生成带有空行的所需输出。

有什么想法吗?谢谢!

-- Generates cumulative total by month by Customer, but only shows when they have a sale
SELECT
Customer_ID, Order_Date, order_id, Order_Amt_Total_USD,
to_char(date_trunc('month', Order_Date), 'Mon YYYY') AS mon_text,
(Select
sum(Order_Amt_Total_USD)
FROM tbl t2
WHERE t2.Customer_ID = t.Customer_ID
AND date_trunc('month', t2.Order_Date) <= t.Order_Date ) AS Cumulative
FROM tbl t
GROUP BY mon_text, Customer_ID, Order_Date, order_id, Order_Amt_Total_USD
ORDER BY date_trunc('month', Order_Date), Customer_ID, Order_Date
;

-- Generates Proper List of All Month IDs for each Customer from entered date through today
WITH temp AS (
SELECT date_trunc('month', Order_Date) AS mon_id
FROM tbl
)
Select
Customer_ID,
to_char(mon_id, 'Mon YYYY') AS mon_text
From tbl,
generate_series('2015-01-01'::date, now(), interval '1 month') mon_id
LEFT JOIN temp USING (mon_id)
GROUP BY mon_id,Customer_ID
;

最佳答案

根据您的描述,您可以将窗口函数与generate_series()结合使用:

SELECT c.Customer_ID, mon,
SUM(Order_Amt_Total_USD) as month_total,
SUM(SUM(Order_Amt_Total_USD)) OVER (PARTITION BY c.Customer_ID ORDER BY mon) as running_total
FROM (SELECT DISTINCT Customer_Id FROM tbl) c CROSS JOIN
generate_series('2015-01-01'::date, now(), interval '1 month') mon LEFT JOIN
tbl t
ON t.Customer_Id = c.customer_id and
date_trunc('month', t.Order_Date) = mon
GROUP BY c.Customer_ID, mon
ORDER BY 1, 2;

Here是一个 SQL fiddle 。

关于sql - 需要帮助为没有订单的月份生成 NULL 条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62602359/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com