简体   繁体   English

如何使用mysql和php计算每个州的总条目数

[英]How to calculate total number of entries per state using mysql and php

I have a table "data" with a column "name" "state" and a few more 我有一个表“数据”,列“名称”“状态”和更多

name     state
peter     MN
john      NY
jay       NY
sam       CO
jack      TX
jill      NO

I want to calculate the number of entries per state and want my output as follows for example: 我想计算每个州的条目数,并希望我的输出如下:

NY: 125
MN: 21
CO: 17
TX: 10
NO: 59

etc... 等等...

I have a query like this 我有这样的查询

$stmt = $db->query("SELECT state, COUNT(*) FROM `data` GROUP BY state;");
$nums = $stmt->rowCount();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr>
       <td>" . $row["state"] . "</td>
       <td>$nums</td>
     </tr>";
}

This displays every state in my table but does not return the corresponding number of entries for that state. 这将显示我表中的每个状态,但不会返回该状态的相应条目数。 This only returns the number of states ie 50. How can I display the number of entries per state? 这只返回状态数,即50.如何显示每个状态的条目数?

$stmt = $db->query("SELECT COUNT(name) as occurances,state FROM `data` GROUP BY state;");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr>
       <td>" . $row["occurances"] . "</td>
       <td>" . $row["state"] . "</td>
     </tr>";
}

Try this version,select the names only 试试这个版本,只选择名称

You seem not to be referring to the column which has the count. 你似乎没有提到有计数的列。 Try aliasing it an referencing the alias in your PHP code: 尝试别名,引用PHP代码中的别名:

$stmt = $db->query("SELECT state, COUNT(*) cnt FROM `data` GROUP BY state;");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "<tr>
       <td>" . $row["state"] . ":</td>
       <td>" . $row["cnt"] . "</td>
     </tr>";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM