Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

mysql - Query to get total orders placed by some specific customer in last year retrieves repeated dates when no order exists

I am working on a query to get total orders placed in last year by some specific customer (id = 329) using two tables viz. orders and calendar (this is to get zero fill values when no corresponding record exists) tables.

orders table:

enter image description here

calendar table:

enter image description here

query:

SELECT c.datefield AS date
     , IFNULL((SELECT COUNT(o.order_date) FROM orders 
WHERE o.customer_id = 329 LIMIT 1), 0) AS TotalOrders 
  FROM calendar AS c 
  LEFT 
  JOIN orders AS o 
    ON c.datefield = DATE(o.order_date) 
WHERE YEAR(c.datefield) = YEAR(CURRENT_DATE - INTERVAL 1 YEAR) 
GROUP
    BY date
     , o.customer_id 
 ORDER 
    BY date ASC 

output:

enter image description here

From above picture, you can see that 2 orders were placed by customer 329 on 2020-01-02. But two extra rows for the same date with 0 order are retrieved. I guess it might be probably from customer 6882, and 670. This is wrong! I only need to fetch orders of customer 329.

How can I exclude these unwanted rows in my query and retrieve total orders by only customer 329?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To count total orders placed monthly in last year by a particular customer, use this query:

SELECT MONTHNAME(c.datefield) AS Month, 
    YEAR(CURRENT_DATE - INTERVAL 1 YEAR) AS Year, 
    IFNULL(o.TotalOrders, 0) AS Orders 
    FROM calendar AS c 
    LEFT JOIN (
        SELECT MONTH(o.order_date) AS Month, 
        YEAR(o.order_date) AS Year, 
        COUNT(o.customer_id) AS TotalOrders 
        FROM orders AS o 
        WHERE YEAR(o.order_date) = YEAR(CURRENT_DATE - INTERVAL 1 YEAR) AND o.customer_id = 329 
        GROUP BY Month) AS o 
    ON MONTH(c.datefield) = o.Month 
    GROUP BY MONTH(c.datefield)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...