SUBTRACT 两列 SUM,然后 SUBTRACT 结果和 SUM 结果以显示最小数量

SUBTRACT two columns SUM, then SUBTRACT the result and SUM the result to show minimum quantity

这个问题有点复杂,但是我需要显示SUBTRACT两列SUM的SUM然后SUBTRACT结果。

现在,当每个产品的最小数量低于 "x" 值时,我得到结果 (1,1,1),但现在显示三个按钮(因为有 3 个产品低于最小数量)和最小数量图例,我只需要显示一个按钮,每个示例 3 个最小数量..

这是我的代码:

$sql = "SELECT SUM(existencia - vendido) AS texist, alert_cantidad FROM PRODUCTOS GROUP BY cod";
$result = $conn->query($sql);
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
    $texist = $row['texist'];
    $alerta = $row['alert_cantidad'];
    $result2 = $texist - $alerta;
    if ($result2 < 0) { 
        echo "<li><a class='btn btn-info' href='alertProduct.php'>
        <i class='glyphicons glyphicons-circle_exclamation_mark'></i>
        " .$result2." minima cantidad
        </a></li>";
    }
}

这里是问题的截图:

我真正需要展示的是:

将您的 SUM 查询放在子查询中,然后在主查询中使用 COUNT(*) 来获取符合条件的数字:

$sql = "SELECT COUNT(*) AS count
        FROM (SELECT SUM(existencia - vendido) AS texist, alert_cantidad 
              FROM PRODUCTOS 
              GROUP BY cod) AS x
        WHERE texist < alert_cantidad";
$result = $conn->query($sql);
$row = $result->fetch(PDO::FETCH_ASSOC);
$count2 = $row['count'];
echo "<li><a class='btn btn-info' href='alertProduct.php'>
    <i class='glyphicons glyphicons-circle_exclamation_mark'></i>
    " .$result2." minima cantidad
    </a></li>";