SELECT
SUM(p.mc_gross) AS totalsales,
SUM(p.tax) AS totlatax,
(SELECT SUM(totalamount) FROM table1
WHERE DATE_FORMAT(paydate, '%d-%m-%Y') =
DATE_FORMAT(p.payment_date, '%d-%m-%Y')) AS totalagentsales,
DATE_FORMAT(p.payment_date, '%d-%m-%Y') AS filter,
(p.mc_gross - p.tax - (SELECT SUM(totalamount) FROM table1)) AS TotalRevenue,
(p.tax + (SELECT SUM(totalamount) FROM table1) ) AS TotalPayment
FROM table2 AS p GROUP BY filter LIMIT 0, 30
此查询总和不会产生正确的结果。我为TotalRevenue
做了减法,为TotalPayment
做了加法。这个结果不正确。
这是我的输出:
totalsales totlatax totalagentsales filter TotalRevenue TotalPayment
38.99 3.54 NULL 11-03-2011 33.152 4.54
6 0.09 NULL 14-02-2011 3.612 1.09
2177.46 197.96 0.899 14-03-2011 1977.202 198.96
299.94 27.27 1.399 15-03-2011 270.372 28.27
19.98 1.82 NULL 21-01-2011 15.862 2.82
3 0.27 NULL 22-01-2011 0.432 1.27
14.77 1.82 NULL 28-02-2011 10.652 2.82
答案 0 :(得分:0)
我不知道你的表格布局,表格中的数据,以及你对你所拥有的内容的了解,我只是在猜测。首先,您可能需要对访问SUM
和mc_gross
的其他实例重复使用tax
。另外,我认为你使用子查询会搞砸你,尤其是SELECT SUM(totalamount) FROM table1
的两个实例。我想你想要限制计算这些总和时使用的行,类似于你对totalagentsales
的处理方式。如果将totalagentsales
子句移动到FROM
子句中,则可以重复使用SELECT SUM(p.mc_gross) AS totalsales, SUM(p.tax) AS totlatax,
q.totalagentsales, DATE_FORMAT(p.payment_date, '%d-%m-%Y') AS filter,
(SUM(p.mc_gross) - SUM(p.tax) - q.totalagentsales) AS TotalRevenue,
(SUM(p.tax) + q.totalagentsales) AS TotalPayment
FROM table2 AS p,
(SELECT SUM(totalamount) totalagentsales FROM table1
WHERE DATE_FORMAT(paydate, '%d-%m-%Y') = DATE_FORMAT(p.payment_date, '%d-%m-%Y')
) AS q
GROUP BY filter
LIMIT 0, 30
值,如下所示:
SELECT SUM(p.mc_gross) AS totalsales, SUM(p.tax) AS totlatax,
q.totalagentsales, DATE_FORMAT(p.payment_date, '%d-%m-%Y') AS filter,
(SUM(p.mc_gross) - SUM(p.tax) - q.totalagentsales) AS TotalRevenue,
(SUM(p.tax) + q.totalagentsales) AS TotalPayment
FROM table2 AS p
LEFT JOIN (SELECT SUM(totalamount) totalagentsales,
DATE_FORMAT(paydate, '%d-%m-%Y') AS filter
FROM table1 GROUP BY filter) AS q
ON DATE_FORMAT(p.payment_date, '%d-%m-%Y') = q.filter
GROUP BY filter
LIMIT 0, 30
修改强>
{{1}}