Query the daily business status of multiple stores within a given period of time, and record 0 if no business

If there is already a store table that contains all the store information, then we can directly use this table in the query without manually listing the name of each store. Here is an example query statement:

SQL statements:

SELECT 
  dates.order_date,
  stores.store_name,
  IFNULL(SUM(orders.amount), 0) AS total_amount
FROM (
  SELECT 
    DATE_ADD('2023-03-01', INTERVAL seq DAY) AS order_date
  FROM (
    SELECT 0 AS seq UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9
  ) seq
  WHERE DATE_ADD('2023-03-01', INTERVAL seq DAY) BETWEEN '2023-03-01' AND '2023-03-08' -- 时间范围
) dates
CROSS JOIN stores
LEFT JOIN orders ON orders.order_date = dates.order_date AND orders.store_name = stores.store_name
GROUP BY dates.order_date, stores.store_name
ORDER BY dates.order_date, stores.store_name;

In the above query statement, we use a CROSS JOIN operation to connect the date sequence and the store table to ensure that each day has a corresponding store name. Then, we used a LEFT JOIN operation to join the date series and store table with the order table to ensure that each day has a corresponding order record, and used the IFNULL function to replace NULL values ​​with 0. Finally, we use the GROUP BY clause to group the results by date and store name and sort them in ascending order by date and store name to get the sales for each day.
 

Guess you like

Origin blog.csdn.net/CSH__/article/details/129604672