I need a little help brainstorming on a query. I have a sales table that has two rows (per day) for each restaurant location. One row is AM sales, and the other is PM sales. The AM sales is literally just the AM sales, however, the PM sales is a combination of the AM sales and the PM sales. So in order to extract the PM sales, you have to subtract the AM sales row from it.
---------------------------------------------------------
date | id | meridiem | daily_sales | cover_counts |
---------------------------------------------------------
2012-03-22 |103 | AM | 2956.32 | 175 |
2012-03-22 |103 | PM | 12124.62 | 484 |
---------------------------------------------------------
I have a query to calculate the projected lunch per person average (which are from the AM sales), and it works great. It basically extracts the first four weeks, from the last 6 weeks of sales data, and averages them. (Note: Per person average is calculated by dividing sales by covers).
$statement = "SELECT directory.location, ROUND((SUM(sales.daily_sales / sales.cover_counts) / 4), 2) AS lppa
FROM t_directory directory
LEFT JOIN t_sales sales
ON sales.site_id = directory.site_id
AND DAYOFWEEK(sales.business_date) = DAYOFWEEK(:date1)
AND sales.business_date < DATE_SUB(:date2, INTERVAL 14 DAY)
AND sales.business_date >= DATE_SUB(:date3, INTERVAL 42 DAY)
AND sales.meridiem = 'AM'
WHERE directory.active = 1
GROUP BY directory.site_id
ORDER BY directory.site_id ASC
LIMIT :totalLocations";
$statementHandle = $this->dbHandle->prepare($statement);
$statementHandle->bindValue(':date1', $this->date, PDO::PARAM_STR);
$statementHandle->bindValue(':date2', $this->date, PDO::PARAM_STR);
$statementHandle->bindValue(':date3', $this->date, PDO::PARAM_STR);
$statementHandle->bindValue(':totalLocations', $this->totalLocations, PDO::PARAM_INT);
$statementHandle->execute();
$lppa = $statementHandle->fetchAll(PDO::FETCH_ASSOC);
Now I want to calculate the dinner per person average. In order to do this, I would have to subtract the AM sales and covers from the PM sales and covers, respectively, before any of the math takes place. Is there a somewhat simple way to implement this all into one query? I can obviously do this with PHP, but I’m just curious as to how this can be accomplished in a query. Any help or insight would be greatly appreciated. Please let me know if any more detail is needed.
You could do to join to t_sales again and then filter for ‘PM’
Note: this solution assumes that
{Site_ID, business_Date, meridiem}is unique