来自mysql的总和

时间:2011-03-22 13:20:33

标签: php mysql sql subquery

 SELECT 
f.nummer AS factuur_id,
f.mvoor AS factuur,
f.faktuurnr AS factuur_nr,
f.topdatum AS factuur_datum,
f.vervaldag AS factuur_vervaldatum,
f.totbruto AS factuur_totaal,
SUM(c.totbruto) AS credit_totaal,
SUM(b.bedrag) AS bedrag_totaal,
f.totbruto - (SUM(c.totbruto) + SUM(b.bedrag)) AS SOM

FROM    ((facturen AS f LEFT JOIN creditnota AS c ON f.nummer = c.nummer)

LEFT JOIN betaling1 AS b ON f.nummer = b.factuurnr)

LEFT JOIN klanten AS k ON f.klantnr = k.nr

WHERE f.betaald = 'N'

AND CURDATE() >= DATE_ADD(f.vervaldag, INTERVAL 15 DAY)

GROUP BY f.nummer

HAVING  (factuur_totaal - (SUM(c.totbruto) + SUM(b.bedrag))) > 0 

ORDER BY k.naam

现在我想从SOM获得SUM 我需要一个子查询吗? 我该怎么做?

我知道我可以循环播放但我想在1次查询中使用它。

mysql,php

谢谢!

2 个答案:

答案 0 :(得分:1)

你可以这样做:

SELECT SUM(SOM) FROM (
    SELECT 
    f.nummer AS factuur_id,
    f.mvoor AS factuur,
    f.faktuurnr AS factuur_nr,
    f.topdatum AS factuur_datum,
    f.vervaldag AS factuur_vervaldatum,
    f.totbruto AS factuur_totaal,
    SUM(c.totbruto) AS credit_totaal,
    SUM(b.bedrag) AS bedrag_totaal,
    f.totbruto - (SUM(c.totbruto) + SUM(b.bedrag)) AS SOM

FROM    ((facturen AS f LEFT JOIN creditnota AS c ON f.nummer = c.nummer)
LEFT JOIN betaling1 AS b ON f.nummer = b.factuurnr)
LEFT JOIN klanten AS k ON f.klantnr = k.nr
WHERE f.betaald = 'N'
AND CURDATE() >= DATE_ADD(f.vervaldag, INTERVAL 15 DAY)
GROUP BY f.nummer
HAVING  (factuur_totaal - (SUM(c.totbruto) + SUM(b.bedrag))) > 0 
ORDER BY k.naam) AS temp

基本上我只是将您的查询包装在SELECT SUM(<some row>) FROM (<your query>) AS temp

答案 1 :(得分:0)

SOM语句换入另一个SUM()来电:

SELECT ...
    SUM(f.totbruto - (SUM(c.totbruto) + SUM(b.bedrag))) AS SOM
...