MYSQL多次计数和求和


MYSQL MULTIPLE COUNT AND SUM

我希望这在MYSQL中是可能的,我正在用PHP编写脚本。

我正试图根据每个月的个别条件和分组,在表1上创建值的SUM和COUNT的多列。表已通过accountid联接。我有两张表每月报告(表1)&花盆(表2)。

所需结果见表1

月度报告(表1)

REPORTID|ACCOUNTID|COMPMONTH|SUMtoDATE|COUNTtoDATE|SUMcompDATE|COUNTcompDATE|
1     |   190     |    JAN    |   150     |      2      |    150      |       2       | 
2     |   190     |    FEB    |     0     |      0      |    100      |       1       |

播种机(表2)

PlanterID | ACCOUNTID |PLANTER |  SALARY |  compDATE  |    toDATE   |
1         |    190    |   aaa  |   100   | Jan-1-2013 | Jan-05-2013 |
2         |    190    |   bbb  |    50   | Jan-9-2013 | Jan-12-2013 |
3         |    190    |   aaa  |   100   | Feb-1-2013 | Mar-12-2013 |
4         |    190    |   bbb  |     0   | Mar-5-2013 | Mar-12-2013 |

带有内部联接的单个查询已经可以工作了,但如果我同时运行这两个查询,我将一无所获,因为如果可能的话,我似乎无法获得逻辑。

这就是我迄今为止所拥有的离stackoverflow不远的东西,但却出现了错误。希望有人能重构它或使它发挥作用。

SELECT *,
(
SELECT COUNT(planters.todate), SUM(planters.todate)
FROM monthlyreport 
INNER JOIN planters ON monthlyreport.accountid = planters.accountid
WHERE monthlyreport.accountid = 190 AND MONTH(monthlyreport.compmonth) = MONTH(planters.todate)
GROUP BY monthlyreport.mthreportid, month(planters.todate)
) AS count_1,
(
SELECT COUNT(planters.compdate), SUM(planters.compdate)
FROM monthlyreport 
INNER JOIN planters ON monthlyreport.accountid = planters.accountid
WHERE monthlyreport.accountid = 190 AND MONTH(monthlyreport.compmonth) = MONTH(planters.compdate)
GROUP BY monthlyreport.mthreportid, month(planters.compdate)
) AS count_2

这不是很清楚,但据我所知,您想要的是在一个查询结果中获得这两个结果。请尝试根据两个表中的accountID加入它们。AS:

SELECT *
from
(select accountID,COUNT(planters.todate) as count2date, SUM(planters.todate) as sum2date
-----
-----) count_1
inner join
(SELECT accountID,COUNT(planters.compdate) as countcomp, SUM(planters.compdate) as sumcomp
-----
-----) count_2
using(accountID);

在count_1或count_2之前不要使用"AS"。最好将外部select查询中的*替换为更具体的属性,如count_1.count2date等。

希望这能有所帮助!如果你还想找什么,一定要告诉我。

-----更新-----

在查看了您上传的文件后,我提出了以下查询:

SELECT count1.compmonth, IFNULL( todatecount, 0 ) , IFNULL( todatesum, 0 ) , IFNULL(      compdatecount, 0 ) , IFNULL( compdatesum, 0 ) 
FROM count_1
LEFT JOIN count_2 ON count_1.compmonth = count_2.compmonth
UNION 
SELECT count2.compmonth, IFNULL( todatecount, 0 ) , IFNULL( todatesum, 0 ) , IFNULL( compdatecount, 0 ) , IFNULL( compdatesum, 0 ) 
FROM count_1
RIGHT JOIN count_2 ON count_1.compmonth = count_2.compmonth

您可以根据自己的意愿格式化0。此外,如果您的数据库平台支持"FULL OUTER JOIN",那么您可以使用它来代替左联接和右联接的并集。

您必须将"FROM count_1"替换为:
FROM (select accountID,COUNT(planters.todate) as count2date, SUM(planters.todate) as sum2date ----- -----) count_1

类似于CCD_ 2。我知道这看起来像是一个巨大的查询,但所做的只是在公共日期连接两个表,并且所有其他不匹配的字段都被指定为NULL。