计算列中的组数

时间:2015-09-15 07:27:06

标签: php mysql sql

使用count()group by我可以生成属于该组的count

示例:

DB

 student_number            sem              SY
    2015-0002            2nd sem          2014-2015
    2015-0002            2nd sem          2014-2015
    2015-0002            2nd sem          2014-2015
    2015-0002            1st sem          2015-2016
    2015-0002            1st sem          2015-2016
    2015-0002            1st sem          2015-2016
    2015-0002            2nd sem          2015-2016
    2015-0002            2nd sem          2015-2016
    2015-0002            2nd sem          2015-2016
    2015-0002            2nd sem          2015-2016

查询

  $sql  = "SELECT *, count(SY) as student_count ";
  $sql .= "FROM studeaccount ";
  $sql .= "WHERE StudentNumber = '2015-0002' ";
  $sql .= "GROUP BY SY, Sem ";
  $sql .= "ORDER BY StudentNumber ASC";

查询上面的输出如下:

2nd sem : 2014-2015 = 3
1st sem : 2015-2016 = 3
2nd sem : 2015-2016 = 4

上面的结果显示组的数量和我想得到的,组的总数。我想输出以下示例。

Group count = 3 // this is what i want to achieve.
希望这有帮助。

2 个答案:

答案 0 :(得分:1)

SELECT COUNT(*) FROM
(
    SELECT *, count(SY) as student_count
    FROM studeaccount
    WHERE StudentNumber = '2015-0002'
    GROUP BY SY, Sem
    ORDER BY StudentNumber ASC
 ) t1

答案 1 :(得分:0)

试试这个

$sql = "select count(distinct sem) from student_account";