如何计算整个表中的多列发生率

时间:2016-05-25 21:07:32

标签: php mysql sql

我有5列包含来自其他表Database table here

的ID的数据

如何计算每个数字在所有记录中出现在整个表中的次数。 我想算上paslauga1,paslauga2,paslauga3,paslauga4,paslauga5数据的发生。 例如,有2条记录有4次1 id 2次2 id 1 time id 3 所以我希望它输出

1 has appeared 4 times
2 has appeared 1 times
3 has appeared 2 times

如果有更多的ID会出现4,5,6等,它也会显示出来。

我需要计算这个,所以我可以在PHP代码上使用它,也许在php中更简单的方法吗?

2 个答案:

答案 0 :(得分:1)

在PHP中使用一个简单的循环来计算数组中的数字。

$counts = array();
$result = $pdo->query("SELECT paslauga1, paslauga2, paslauga3, paslauga4, paslauga5 FROM yourTable");
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    foreach ($row as $col) {
        if ($col !=== null) {
            if (isset($counts[$col])) {
                $counts[$col]++;
            } else {
                $counts[$col] = 1;
            }
        }
    }
}
ksort($counts);
foreach ($counts as $id => $c) {
    echo "$id has appeared $c times<br>";
}

答案 1 :(得分:0)

SELECT paslauga, count(paslauga)
FROM (
       SELECT paslauga1 as paslauga FROM yourTable
       UNION ALL
       SELECT paslauga2 as paslauga FROM yourTable
       UNION ALL
       SELECT paslauga3 as paslauga FROM yourTable
       UNION ALL
       SELECT paslauga4 as paslauga FROM yourTable
       UNION ALL
       SELECT paslauga5 as paslauga FROM yourTable
     ) T
GROUP BY paslauga