对于给定年份,每月的行数

时间:2016-02-10 07:38:05

标签: php mysql

我想选择每月注册。

<?php
include 'member_entry/sdg_connect.php';

$sql="select member_id from sdg_members where member_joindate BETWEEN  DATE('2015-02-30') AND DATE( '2016-12-31')";

if ($result=mysqli_query($conn,$sql))
  {
      $rowcount=mysqli_num_rows($result);
      echo $rowcount;

      mysqli_free_result($result);
  }

  mysqli_close($conn);
 ?>

3 个答案:

答案 0 :(得分:3)

您可以使用聚合函数count()并按月分组

$sql="select count(member_id), month(member_joindate) 
from sdg_members
where member_joindate BETWEEN  str_to_date('30/02/2015', '%d/%m/%Y')
    AND    str_to_date('31/12/2016', '%d/%m/%Y')  
group by month(member_joindate) ";

答案 1 :(得分:1)

正如已经提到的scaisEdge,您必须使用group by

select
  YEAR(member_joindate) AS year, MONTH(member_joindate) AS month, COUNT(DISTINCT member_id) AS joins
from
  sdg_members
where
  member_joindate BETWEEN '2015-02-30' AND '2016-12-31'
group by
  YEAR(member_joindate), MONTH(member_joindate)

这将以

的形式为您提供结果
year | month | joins
2015 |     3 |    10
2015 |     4 |     3
2015 |     5 |    11
...

之后您不再需要申请num_rows了,您只需要完成结果集

答案 2 :(得分:0)

如果member_joindate列的数据类型仅为DATE,则可以使用此查询:

SELECT COUNT(member_id), MONTH(member_joindate) 
from sdg_members
where member_joindate BETWEEN '2015-02-30' AND '2016-12-31'   
group by MONTH(member_joindate)

如果member_joindate列的数据类型仅为DATETIME,则可以使用此查询:

SELECT COUNT(member_id), MONTH(member_joindate) 
from sdg_members
where member_joindate BETWEEN '2015-02-30 00:00:00' AND '2016-12-31 23:59:59'   
group by MONTH(member_joindate)

请注意MONTH()会返回月份编号,您也可以使用MONTHNAME()功能。

SELECT COUNT(sb_id), MONTHNAME(sb_ondate) 
from sbbleads_members
where sb_ondate BETWEEN '2015-02-30' AND '2016-12-31'   
group by MONTHNAME(sb_ondate);