簡體   English   中英

MYSQL查詢每周獲取新客戶

[英]MYSQL query to get new customers each week

我正在為每周如何獲得新客戶(以前從未訂購過)的報告而苦苦掙扎。 結果應如下所示:

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

現在,回到我的查詢。 我希望每周都能找到新客戶。 我遇到的問題是我無法弄清楚如何將一年中的每個星期放在查詢中以便比較訂單日期。 舊訂單是 “本周” 之前發生的訂單,新訂單是 “本周”發生的訂單。 當我使用靜態日期時,查詢工作正常,但是我正在努力使日期可變,即一年中的每個星期。 在有挑戰的查詢中查看我的問題。

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

我將首先使用聚合子查詢來計算每個客戶的第一筆訂單日期,然后將結果與日歷表結合起來:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM