簡體   English   中英

MYSQL多個計數和總和

[英]MYSQL MULTIPLE COUNT AND SUM

我希望這在MYSQL中是可行的,我正在使用PHP編寫腳本。

我正在嘗試根據每個月的具體條件和分組,在值的總和和table1的COUNT上創建多個列。 這些表已通過accountid聯接。 我有兩個表monthlyreport(table1)和planters(table2)。

所需結果在表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加入它們:

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”。 最好將外部選擇查詢中的*替換為更具體的屬性,例如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

對於FROM count_2同樣。 我知道這看起來像一個巨大的查詢,但是所有這些都是在共同的日期聯接2個表,而所有其他不匹配的字段都被指定為NULL。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM