How can i get count of customers per day by unique and repeat customer for specific date?

前端 未结 3 1329
悲哀的现实
悲哀的现实 2021-01-07 14:32

I am trying to get a result from my order table to get list of counts of customers who 1st time ordered and repeat orders. Something like below.

Date               


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-01-07 15:27

    You can get the total orders per day by grouping on OrderDate:

    SELECT OrderDate, COUNT(OrderNumber) AS total FROM orders GROUP BY OrderDate
    

    And you can get the no. of first orders per day from the following query :

    SELECT OrderDate, COUNT(q1.CustomerID) AS first FROM (SELECT CustomerID, min(OrderDate) AS OrderDate FROM orders GROUP BY CustomerID)q1 GROUP BY q1.OrderDate
    

    Now join these two on OrderDate to get the distribution of first and repeated orders :

    SELECT a.OrderDate, a.first, (b.total - a.first) AS repeated FROM
    (SELECT OrderDate, COUNT(q1.CustomerID) AS first FROM (SELECT CustomerID, min(OrderDate) AS OrderDate FROM orders GROUP BY CustomerID)q1 GROUP BY q1.OrderDate)a
    JOIN
    (SELECT OrderDate, COUNT(OrderNumber) AS total FROM orders GROUP BY OrderDate)b
    on(a.OrderDate = b.OrderDate)
    

提交回复
热议问题