我一直在努力获取每周新客户(以前从未下过订单的客户)的报告。结果应如下所示:
WEEK_ENDING_DATE NEW_CUSTOMERS
---------------- -------------
2019-02-03 50
2019-02-10 60
我的查询对old_orders和new_orders进行了右外部联接以查找新客户(请参见下面的查询)。
我还有一个名为my_calendars的帮助程序表,可以帮助我按week_end_date进行分组。 my_calendars表中的行包含一年中的每个日期,该日期的相应week_begin_date和week_end_date。例如,对于像2019-02-15这样的日期,week_begin_date是2019-02-11,week_end_date是2019-02-17(Week是Mon-Sun,格式= YYYY-MM-DD)。帮助器表如下所示:
DATE WEEK_BEGIN_DATE WEEK_END_DATE
---------- ---------------- -------------
2019-02-15 2019-02-11 2019-02-17
2019-01-08 2019-01-07 2019-01-13
现在,返回我的查询。我希望每周都能找到新客户。我遇到的问题是我无法弄清楚如何将一年中的每个星期放在查询中以便比较订单日期。 old_orders是在 之前的“本周”发生的订单,new_orders是在“本周”发生的那些订单。当我使用静态日期时,查询工作正常,但是我正努力使日期可变,即一年中的每个星期。在有挑战的查询中查看我的问题。
SELECT
new_orders.week_end_date
,COUNT(DISTINCT new_orders.customer) AS new_customers
FROM
(SELECT *
FROM orders old
INNER JOIN my_calendar cal ON cal.date = old.order_date
#The line below works, but it's a static date of Feb 4. How do I replace it with each week in the calendar
WHERE cal.week_end_date < '2019-02-04'
#The commented line below does not work
#WHERE cal.date < cal.week_end_date
) AS old_orders
RIGHT OUTER JOIN (SELECT *
FROM order_items_view new
INNER JOIN my_calendar cal ON cal.date = new.order_date
#How do I replace the static dates below and compare with each week in the calendar
WHERE cal.date BETWEEN '2019-02-04' and '2019-02-10'
#The commented line below didn't work
#WHERE cal.week_end_date = cal.week_end_date
) AS new_orders
ON new_orders.customer = old_orders.customer
WHERE old_orders.customer IS NULL
GROUP BY new_orders.week_end_date
答案 0 :(得分:0)
我将首先使用聚合子查询来计算每个客户的第一笔订单日期,然后将结果与日历表结合起来:
SELECT
c.week_end_date,
COUNT(o.customer) AS new_customers
FROM
my_calendar AS c
LEFT JOIN (
SELECT customer, MIN(order_date) first_order_date
FROM orders
GROUP BY customer
) AS o ON c.date = o.first_order_date
GROUP BY c.week_end_date