Ad
How To Outer Join A Calendar Table To View Dates With 0 Records
I have a table with records of orders by customers and a table with dates from Jan 2022 to 10 years. I wanted to get all numbers of customers made everyday for the last 28 days, including those with 0 customers recorded. So I needed to outer join the calendar table to the customer records. However, I cant use outer join correctly.
Here's how I done it:
SELECT order_date as 'date', COUNT(orderstatus) as 'customers'
FROM orders
RIGHT OUTER JOIN calendar ON
calendar.date = orders.order_date
WHERE sellerid = 11
Im getting:
date customers
2022-01-02 9
I wanted to see:
date customers
2022-01-01 0
2022-01-02 9
2022-01-03 0
.
.
.
Ad
Answer
You would not get the results that you posted in your question unless you group by date, so I guess you missed that part of your code.
You need a WHERE
clause to filter the calendar's rows for the last 28 days and you must move the condition sellerid = 11
to the ON
clause:
SELECT c.order_date,
COUNT(o.order_date) customers
FROM calendar c LEFT JOIN orders o
ON o.sellerid = 11 AND o.order_date = c.date
WHERE c.date BETWEEN CURRENT_DATE - INTERVAL 28 DAY AND CURRENT_DATE
GROUP BY c.order_date;
Ad
source: stackoverflow.com
Related Questions
- → October CMS - SQL request incompatible with sql_mode=only_full_group_by
- → How to get a list of similar items
- → Laravel GroupBy using database table column values
- → Finding the closest date given a date in a groupby dataframe (Python)
- → Group by with extra features MySQL
- → MySQL JOIN with where clause and group by count
- → Group by in mysql [some stuff to foo the bot]
- → Join 2 tables for viewing
- → How to delete frozen values from a table in MYSQL
- → MySQL COUNT records before GROUP BY
- → MySQL - Selecting the items that have the highest count of trips but not repeated
- → Get first and last record number in every date exists in table
- → SQL query to select percentage per Group
Ad