1

我在论坛上搜索过,但是所有答案似乎都不适用于我我猜这是更多的用户错误。

我正在尝试做的事情:

  1. 从 MySQL 中检索数据集

  2. 计算总行数

  3. 具体计算其中有多少在metSLA列中具有值“Y”

  4. 具体计算其中有多少在metSLA 列中具有值“N”

  5. 将这些metSLA值中的每一个转换为百分比

** MySQL 查询确实有效,并将其存储在变量 $result 中以供参考。

*

        //sla and total case count and percentages
        $sla_met_rows = 0;
        $sla_not_met_rows = 0;

        $total_cases = mysql_num_rows($result);

        while ($row = mysql_fetch_array($result)) 
        {
        if `metSLA` = "Y"
            {
            $sla_met_rows ++;
            } else if `metSLA` = "N"
                {
                $sla_not_met_num_rows ++;
                }
        }
        $met_percentage = 100 / $total_cases * $sla_met_rows;
        $not_met_percentage = 100 / $total_cases * $sla_not_met_num_rows;
4

2 回答 2

5

You can use a single MySQL query to get the percentage result:

SELECT COUNT( CASE WHEN `metSLA` = "Y" THEN 1 ELSE NULL END ) AS `Yes`,
    COUNT( CASE WHEN `metSLA` = "N" THEN 1 ELSE NULL END ) AS `No`,
    COUNT(1) AS `total`
FROM `TableName`

In your PHP, it'll be referenced as:

$result = mysql_query( <<The query above is here>> );
$row = mysql_fetch_array( $result );
$met_precentage = $row['Yes'] * 100 / $row['total'];
$not_met_precentage = $row['No'] * 100 / $row['total'];
于 2013-03-29T17:56:52.493 回答
1

改变

    if `metSLA` = "Y"
        {
        $sla_met_rows ++;
        } else if `metSLA` = "N"
            {
            $sla_not_met_num_rows ++;
            }

到:

    if ($row['metSLA'] == "Y")
    {
      $sla_met_rows ++;
    }

    else if ($row['metSLA'] == "N")
    {
      $sla_not_met_num_rows ++;
    }

你有三个问题:

  1. 您缺少条件周围的括号,
  2. 您正在分配 ( =) 而不是比较 ( ==),并且
  3. You're running a shell command rather than getting the value from the database row.
于 2013-03-29T17:56:23.037 回答