在MYSQL中,我希望获得具有多个条件的多个SUM来完成总计并获得价格里程碑

时间:2014-06-15 10:26:32

标签: php mysql sql ezsql

这是我的SQL代码。我已选择每行的价格和每行的里程碑以及加入表格的ID,但我只有一行的结果。

用于执行多个过滤器的PHP代码:

if($i==0)
{
    if($fc == "projet")
    {
        $filtre_bdd .= "AND p.$fc = '$fv' ";
    }
    else 
    {
        $filtre_bdd .= "AND cible.$fc = '$fv' ";
        $i= $i + 2;
    }
}

SQL查询:

SELECT cible.prix,a.valeur,a.idroute,cible.id,p.id,
    SUM(DISTINCT a.valeur) AS total_avances, /* the milestone sum the unique one */
    SUM(a.valeur) AS total_avance, /* the milestone sum of each row */
    SUM(cible.prix) AS total_prix /* the price sum */
FROM avances AS a,routes AS cible,projets AS p
WHERE a.idroute = cible.id AND p.id = cible.idprojet $filtre_bdd /* the conditions to join the tables and do the filter */
GROUP BY cible.id, a.idroute 
HAVING total_avances <> cible.prix AND cible.prix - total_avances >- 1 

现在我如何才能获得所有这些条件的价格总数和里程碑总数?目标表包含项目的ID和里程碑的ID。我们必须对每一行的里程碑和总和进行总和,并将其与项目价格进行比较。

2 个答案:

答案 0 :(得分:0)

尝试使用以下查询: -

SELECT DISTINCT cible.prix, a.valeur, a.idroute, cible.id, p.id,
SUM(a.valeur) AS total_avances,
SUM(a.valeur) AS total_avance,
SUM(cible.prix) AS total_prix
FROM avances a INNER JOIN routes ciblE ON a.idroute = cible.id
INNER JOIN projets p ON p.id = cible.idprojet
GROUP BY cible.prix, a.valeur, a.idroute, cible.id, p.id,
HAVING total_avances <> cible.prix AND cible.prix - total_avances >- 1 

希望这可以帮到你。

答案 1 :(得分:0)

我找到了解决方案,谢谢

SELECT SUM(alucard.uu) as total_prix,SUM(alucard.vv) as total_avances FROM(
                                SELECT ultimate.id,SUM(ultimate.prix) as uu,SUM(ultimate.valeur) as vv FROM(
                                    SELECT e.id,e.prix,e.idprojet,e.valeur FROM(
                                        SELECT cible.id,cible.prix,cible.idprojet,a.valeur=4 AS valeur FROM avances AS a
                                            INNER JOIN routes cible ON a.idroute=cible.id 
                                            INNER JOIN projets p ON p.id=cible.idprojet $filtre_bdd 
                                             $date_bdd
                                            GROUP BY cible.id) AS e
                                    UNION 

                                    SELECT cible.id,cible.prix=4,cible.idprojet,SUM(a.valeur) FROM avances as a
                                        INNER JOIN routes cible ON a.idroute=cible.id 
                                        INNER JOIN projets p ON p.id=cible.idprojet $filtre_bdd 
                                        $date_bdd
                                        GROUP BY cible.id) AS ultimate
                                    GROUP BY ultimate.id
                                    HAVING SUM(ultimate.prix)>SUM(ultimate.valeur) ) AS alucard