简体   繁体   English

按行对表分组的列进行计数

[英]Count column of table group by rows

I can count number of a table rows by using mysqli_num_rows . 我可以使用mysqli_num_rows来计数表的行 I have a table which contains similar rows. 我有一个包含相似行的表。 How can I count by grouping by similar row? 如何按相似的行分组进行计数? For instance: I have a table with 2 columns : Student and Option . 例如:我有一个包含2列的表格: Student和Option Let say there are 50 students. 假设有50个学生。 20 are in Economy option, 20 are in Management option and 10 are in Secretary Option. 经济选项为20,管理选项为20,秘书选项为10。 How can display those numbers. 如何显示这些数字。 I can display only the 50. 我只能显示50。

my codes 我的密码

$qry = "select * from table group by option";
$req= @mysqli_query($conn, $qry); 

$result = mysqli_query( $conn, "select id from table");
$num_rows = mysqli_num_rows($result); 

Students Total (<?php echo $num_rows ?>)

<table >
    <tr>
        <th>Student</th>
        <th>Option</th>
    </tr>
    <?php
    while($row=mysqli_fetch_array($req))

    {
    ?>
    <tr>
        <td><?php echo $row['student'] ?></td>
        <td><?php echo $row['option'] ?></td>
    </tr>
    <?php
    }
    ?>
</table>

Here is the query you need: 这是您需要的查询:

SELECT COUNT(*) AS `option_count`, * -- returns a count aliased as "options_count"
FROM `table`
GROUP BY `option` -- will group the options and show the counts

Now you can echo the count, along with other data: 现在,您可以回显计数以及其他数据:

echo $row['count_options'];
echo $['options'];

The problem that you have here is that you will not be able to display each student in the option because this counts / groups only the three options. 这里的问题是您将无法显示该选项中的每个学生,因为这仅对三个选项进行计数/分组。

看到正确的查询:

$qry = "select option as opt, COUNT(*) AS option from table group by option";

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

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