我正在尝试运行一份报告,该报告将为我提供过去 3 个月的每日“情节”销售额,但我很难让 SUM() 正确加起来。单个 Transaction_ID 可能跨越多个 Plot 记录。通过下面的查询,如果有 2 个具有相同 Transaction_ID 的地块,则将它们加在一起,这不是我想要的。我需要它在 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
表结构如下所示:
+-----------------------------------+----------------------------------------------------------------------------------------------------+------+-----+---------------------+----------------+
| 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 | |
+------------------------+-------------+------+-----+---------------------+----------------+