0

当涉及到“注册日期后 1 和 2 个月内”时,我很难找到总数。我希望对我当前的代码提供一些帮助和一些反馈。没有错误,只是不知道如何解决这个问题

问题是:求在注册日期后 1 个月和 2 个月内 1 月份注册的每位会员的平均收入

数据表为:

表 1:成员资格

member_id (PK) int signup_date datetime join_country varchar(2) email varchar cancel_date date expiry_date date

表 2:交易

transaction_id (PK) int member_id int transaction_date datetime transaction_type_ID int product_id int transaction_amount float

当前代码:

SELECT AVG (t.transaction_amount) AS AVG_REV, 
    COUNT(m.member_id) AS Member_ID
    FROM transactions AS t
    INNER JOIN memberships AS m
    ON m.member_id = t.member_id 
    WHERE m.signup_date BETWEEN '2018-01-01' AND '2018-01-31'
    GROUP BY m.member_id
;
4

2 回答 2

0
SELECT 
    m.member_id,
    AVG(CASE WHEN t.transaction_date <= m.signup_date + '1 month'::interval THEN t.transaction_amount END) AS AVG_1ST_MONTH, 
    AVG(CASE WHEN t.transaction_date > m.signup_date + '1 month'::interval AND t.transaction_date <= m.signup_date + '2 month'::interval THEN t.transaction_amount END) AS AVG_2ND_MONTH
FROM transactions AS t
INNER JOIN memberships AS m
    ON m.member_id = t.member_id 
WHERE m.signup_date BETWEEN '2018-01-01' AND '2018-01-31'
GROUP BY m.member_id

此外,原始查询中这部分的别名没有意义:COUNT(m.member_id) AS Member_ID- 这实际上会计算每个成员的记录数(你可以说事务数),所以我不确定你为什么命名它Member_ID

于 2021-07-01T14:11:01.237 回答
0

查找在注册日期后 1 个月和 2 个月内 1 月份注册的每位会员的平均收入

这听起来像您想要两个数字:注册后 1 个月的平均收入和注册后两个月的平均收入。每个人真的没有“平均收入” member_id。每个成员都有一个收入,然后是所有成员的平均值

我认为最好的方法是按成员汇总收入,然后取平均值。按成员划分,这些期间的总收入为:

SELECT m.member_id,
       SUM(t.transaction_amount) AS member_revenue, 
       SUM(t.transaction_amount) FILTER (WHERE t.transaction_date < m.signup_date + interval '1 month') AS member_revenue_month_1,
       SUM(t.transaction_amount) FILTER (WHERE t.transaction_date < m.signup_date + interval '2 month') AS member_revenue_month_2
FROM transactions t JOIN
     memberships m
     ON m.member_id = t.member_id 
WHERE m.signup_date >= '2018-01-01' AND
      m.signup_date < '2018-02-01'
GROUP BY m.member_id;

然后,再次汇总总体平均值:

SELECT AVG(member_revenue_month_1),
       AVG(member_revenue_month_2)
FROM (SELECT m.member_id,
             SUM(t.transaction_amount) AS member_revenue, 
             SUM(t.transaction_amount) FILTER (WHERE t.transaction_date < m.signup_date + interval '1 month') AS member_revenue_month_1,
             SUM(t.transaction_amount) FILTER (WHERE t.transaction_date < m.signup_date + interval '2 month') AS member_revenue_month_2
      FROM transactions t JOIN
           memberships m
           ON m.member_id = t.member_id 
      WHERE m.signup_date >= '2018-01-01' AND
            m.signup_date < '2018-02-01'
      GROUP BY m.member_id;
     ) m
于 2021-07-01T14:37:14.547 回答