I’m attempting to run a report which will give me daily “plot” sales over the past 3 months and I’m having a hard time getting SUM() to add up correctly. A single Transaction_ID may span across several Plot records. With the query below, if there are 2 plots with the same Transaction_ID, it is adding them together, which is not what I want. I need it to only use a Transaction row once within the SUM().
SELECT
DATE_FORMAT(Transactions.CreateDate,'%m-%d') AS MonthAndDay,
DATE_FORMAT(Transactions.CreateDate,'%M, %D') AS Day,
SUM(Transactions.AmountTotal) AS DailySales
FROM
Transactions,
Plots
WHERE
Transactions.Transaction_ID = Plots.Transaction_ID AND
Transactions.CreateDate <= CURDATE() AND
Transactions.CreateDate >= DATE_SUB(CURDATE(),INTERVAL 3 MONTH)
GROUP BY
MonthAndDay
ORDER BY
MonthAndDay ASC
The table structures look like so:
+-----------------------------------+----------------------------------------------------------------------------------------------------+------+-----+---------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------------------------+----------------------------------------------------------------------------------------------------+------+-----+---------------------+----------------+
| Transaction_ID | int(11) | NO | PRI | NULL | auto_increment |
| CreateDate | datetime | NO | | 0000-00-00 00:00:00 | |
| AmountTotal | decimal(10,2) | NO | | 0.00 | |
+-----------------------------------+----------------------------------------------------------------------------------------------------+------+-----+---------------------+----------------+
+------------------------+-------------+------+-----+---------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------------+-------------+------+-----+---------------------+----------------+
| Plot_ID | int(11) | NO | PRI | NULL | auto_increment |
| Transaction_ID | int(11) | YES | MUL | NULL | |
| Plot | varchar(10) | NO | | 0 | |
+------------------------+-------------+------+-----+---------------------+----------------+
The following solution works, albeit with a subquery: