Good Day,
I have a table that contains 3 columns. Date, Store, Straight_Sales. Each day a new record is created for each store with their previous day's sales.
What I am trying to do is generate a result set that has both current month to date sales for each location as well as the past year same MTD sales.
I can accomplish this by using two totally separate queries and result sets however I am trying to include these in the same query for reporting purposes.
Here are my two current queries that work just fine:
Last Year Month to Date:
SELECT SUM(summ_sales_daily.straight_sales), store_master.name
FROM
store_master
INNER JOIN summ_sales_daily ON store_master.unit = summ_sales_daily.store
WHERE YEAR(date)=YEAR(DATE_SUB(NOW(), INTERVAL 1 YEAR)) AND MONTH(date)=MONTH(NOW())
GROUP BY summ_sales_daily.store ORDER BY summ_sales_daily.store
Current Year Month to Date:
SELECT SUM(summ_sales_daily.straight_sales), store_master.name
FROM
store_master
INNER JOIN summ_sales_daily ON store_master.unit = summ_sales_daily.store
WHERE YEAR(date)=YEAR(NOW()) AND MONTH(date)=MONTH(NOW())
GROUP BY summ_sales_daily.store ORDER BY summ_sales_daily.store
I'd like these to return the current and previous years MTD in the same result along with the store name (hence the join)
Any help would be awesome!
Using MariaDB
You can either use conditional aggregation and move the different conditions into a case expression within the sum function:
SELECT
store_master.name
, SUM(CASE WHEN YEAR(date)=YEAR(DATE_SUB(NOW(), INTERVAL 1 YEAR)) THEN summ_sales_daily.straight_sales ELSE 0 END) last_year_sales
, SUM(CASE WHEN YEAR(date)=YEAR(NOW()) THEN summ_sales_daily.straight_sales ELSE 0 END) current_year_sales
FROM store_master
INNER JOIN summ_sales_daily ON store_master.unit = summ_sales_daily.store
WHERE MONTH(date)=MONTH(NOW())
GROUP BY summ_sales_daily.store
ORDER BY summ_sales_daily.store;
Or you can calculate the two different values in a couple of derived tables that you join with:
SELECT
store_master.name,
last_year.sales as previous_mtd,
current_year.sales as current_mtd
FROM store_master
LEFT JOIN (
SELECT store, SUM(straight_sales) sales
FROM summ_sales_daily
WHERE YEAR(date)=YEAR(DATE_SUB(NOW(), INTERVAL 1 YEAR)) AND MONTH(date)=MONTH(NOW())
GROUP BY store
) last_year ON store_master.unit = last_year.store
LEFT JOIN (
SELECT store, SUM(summ_sales_daily.straight_sales) sales
FROM summ_sales_daily
WHERE YEAR(date)=YEAR(NOW()) AND MONTH(date)=MONTH(NOW())
GROUP BY store
) current_year ON store_master.unit = current_year.store ;
The first solution would probably perform better.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.