在不同的列mysql中计算相同的值

时间:2014-02-24 03:40:41

标签: php mysql sql count sum

我需要计算在相同ID的不同列中成熟的相同值的次数。 我将尝试用一个例子来澄清: 表格

+-----+-----+-----+-----+-----+
|  id | d01 | d02 | d03 | d04 |
+=====+=====+=====+=====+=====+
|  1  |  A  |  A  | B   |  B  | 
+-----+-----+-----+-----+-----+
|  2  |  A  |  A  |  A  |  A  | 
+-----+-----+-----+-----+-----+
|  3  |  B  |  B  |  A  |  A  | 
+-----+-----+-----+-----+-----+
|  4  |  A  |  A  |  A  |  A  | 
+-----+-----+-----+-----+-----+
|  5  |  A  |  A  |  A  |  A  | 
+-----+-----+-----+-----+-----+
|  6  |  B  |  A  |  A  |  A  | 
+-----+-----+-----+-----+-----+

我需要知道“ B ”值重复多少次任何人(ID) ..

这可能吗?的结果

+-----+-----+-----+
|  id |  count B  |
+=====+=====+=====+
|  1  |     2     |
+-----+-----+-----+
|  2  |     0     |
+-----+-----+-----+
|  3  |     2     |
+-----+-----+-----+

我正在考虑使用“SUM”功能,但我不知道如何只显示单个ID。 在此先感谢,希望问题很清楚!

2 个答案:

答案 0 :(得分:3)

如果只有四列:

SELECT id, (d01 = 'B') + (d02 = 'B') + (d03 = 'B') + (d04 = 'B')
FROM tablename
  

没有31列

这是一个你可以通过两种方式解决的问题:

  1. 重复其他27列的条件:)
  2. 规范化您的结构,以便每个值都依赖于id和表示日历的数值。
  3. PHP方式

    您还可以获取所有列,让PHP为您解决此问题:

    $res = $db->query('SELECT * FROM tablename');
    foreach ($res->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $id = $row['id'];
        unset($row['id']); // don't count the id column
        $count = count(array_keys($row, 'B', true));
    
        printf("ID %d: %d\n", $id, $count);
    }
    

答案 1 :(得分:1)

因为你似乎在使用mysql _ *:

// SHOW COLUMNS returns all the columns and constrains of the defined table
// We only need the column names so we will be later calling it by 'Field'
$sql = mysql_query("SHOW COLUMNS FROM table"); //your table name here
$val_to_count = 'B'; //value to count here
$id = 1; //id to search for
$new_sql = 'SELECT id, ';

// In this loop we will construct our SELECT query using the columns returned 
// from the above query
while($row=mysql_fetch_array($sql)){
    if($row['Field']!='id'){
            $new_sql .= ' ('.$row['Field'].' = "'.$val_to_count.'") + ';
    }
}

//Removing the last "+ " produced in the select query
$new_sql = rtrim($new_sql,"+ ");
$new_sql .= ' as count FROM table WHERE id = '.$id; //table name here again
// so $new_sql now has an output like: 
// SELECT ID, (d01 = 'B') + (d02 = 'B') ... WHERE id = 1

$sql2 = mysql_query($new_sql);
//executing the constructed query with the output below
while($row2=mysql_fetch_array($sql2)){
 echo 'ID - '.$row2['id']."<br>";
 echo 'Count - '.$row2['count']."<br>";
}

注意:

mysql_ * 已弃用,请考虑迁移到mysqli_*