Avatar of dannyg280
dannyg280
Flag for United States of America asked on

MySQL Query - How to Get Data From Current Month and Same Month Last Year?

I have a simple query that sums sales totals for September and compares them with Sept of last year. How can I write this so that it auto updates with the current month month each month?

Select Salesman,
 SUM(CASE WHEN InvoiceDate Between '2015-9-1' and '2015-9-30' THEN Totsales else 0 end) as Sales15,
 SUM(CASE WHEN InvoiceDate Between '2016-9-1' and '2016-9-30' THEN Totsales else 0 end) as Sales16
 from vCustomerInvoiceDetail
Group by Salesman

Open in new window


This is part of a PHP script so if there's a better/easier way to do it in PHP I'd be happy to hear about that as well.

Thank You!
PHPSQL

Avatar of undefined
Last Comment
dannyg280

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Ferruccio Accalai

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Julian Hansen

I think this is what you asked for - not sure it is what you want. For this to mean anything it would need to run on the last day of the month. Otherwise if you want to look back at the last month it would require some tweaking.
SELECT Salesman,
 SUM(CASE WHEN InvoiceDate BETWEEN CONCAT(YEAR(NOW())-1, '-', MONTH(NOW()), '-01') AND CONCAT(YEAR(NOW())-1, '-', MONTH(NOW()), '-', DAY(LAST_DAY(NOW()))) THEN Totsales ELSE 0 END) AS Sales15,
 SUM(CASE WHEN InvoiceDate BETWEEN CONCAT(YEAR(NOW()), '-', MONTH(NOW()), '-01') AND CONCAT(YEAR(NOW()), '-', MONTH(NOW()), '-', DAY(LAST_DAY(NOW()))) THEN Totsales ELSE 0 END) AS Sales16
 FROM vCustomerInvoiceDetail
GROUP BY Salesman

Open in new window

dannyg280

ASKER
Worked great! Thank You!
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23