2016-02-12 87 views
0

我可以通过使用mysqli_num_rows来统计表行数。我有一张包含相似行的表格。我怎样才能通过类似的行分组?例如:我有一个2列的表格:学生和选项。假设有50名学生。 20个在经济选项中,20个在管理选项中,10个在秘书选项中。如何显示这些数字。我可以只显示50按行计算表组的列数

我的代码

$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> 
+0

您需要由option'加上'GROUP到您的查询的末尾。 –

+0

好吧,我忘了添加时,我张贴组。但如何通过添加每个组的计数数字列? – branche

回答

1

以下是你需要查询:

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 

现在你可以重复计数,以及其他数据:

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

你在这里遇到的问题是你不会无法显示每个学生选项,因为这只会计算/分组三个选项。

+0

我尝试去做。只显示计数值,但选项名不显示。显然我只想要列选项和计数值显示..你介意帮助我更多? – branche

0

看哪合适的查询:

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