You can achieve this by joining the two tables on Client and Customer, and then use the TIMESTAMP_TRUNC and INTERVAL functions to filter the task dates that fall within the previous month of the invoice date.
Here’s how you can modify your SQL query:
SELECT h.tasks, h.date AS taskdate, q.date AS invoicedate FROM Activitytable h LEFT JOIN invoice_table q ON h.Client = q.Customer WHERE h.date >= TIMESTAMP_TRUNC(TIMESTAMP(q.date), MONTH) - INTERVAL 1 MONTH AND h.date < TIMESTAMP_TRUNC(TIMESTAMP(q.date), MONTH)
This query works as follows:
TIMESTAMP_TRUNC(TIMESTAMP(q.date), MONTH): This function truncates theq.dateto the first day of the month.TIMESTAMP_TRUNC(TIMESTAMP(q.date), MONTH) - INTERVAL 1 MONTH: This calculates the first day of the previous month.h.date >= TIMESTAMP_TRUNC(TIMESTAMP(q.date), MONTH) - INTERVAL 1 MONTH AND h.date < TIMESTAMP_TRUNC(TIMESTAMP(q.date), MONTH): This condition filters the tasks that fall between the first day of the previous month and the first day of the current month.