如何在mysql中按当月的当前年份计算总数

时间:2015-12-03 08:24:17

标签: mysql count

我有以下代码表格格式。

表名: - wp_lead_count_freevendor

id entryid start_date end_date   user_id count_set entry_date cancel_set_date
70 11392   2015-12-03 2015-12-03 3185            1 2015-12-03 2015-12-04
71 11393   2015-12-03 2015-12-03 3185            1 2015-12-03 2015-12-04
72 11394   2014-10-01 2014-10-01 3185            1 2014-10-01 2014-10-01

在这里,我想计算总计count_set列。当月和年start_dateWHERE user_id = 3185。

假设start_date当前年份为2015年&当月是12: -

year   month   count total 
2015    12     2

对于一年中这个月的用户ID 3185 count_set总计= 2

所以任何正文都会告诉我如何触发查询以获得count_set = 3185当月当前年度的总数user_id

我尝试了以下查询,但它无法正常工作。

    $check_per_month=mysql_query("SELECT DATE_FORMAT(end_date, '%Y') as 'year',
    DATE_FORMAT(end_date, '%m') as 'month',
    COUNT(id) as 'total'
    FROM wp_lead_count_freevendor WHERE user_id=$wp_lead_count_user_id
    GROUP BY DATE_FORMAT(end_date, '%Y%m')") OR DIE(mysql_error());
    while($row = mysql_fetch_assoc($check_per_month))
    {

    echo $sql_chk_current_month_count=$row['total'];

    }

2 个答案:

答案 0 :(得分:1)

尝试使用这样的where,year和month方法计算:

SELECT .... WHERE YEAR(start_date)=2015 AND MONTH(start_date)=12

答案 1 :(得分:0)

尝试此查询:

  SELECT YEAR(NOW()) as `year`,MONTH(NOW()) as `month', SUM(count_set) as `count_set`
  From  wp_lead_count_freevendor
     WHERE YEAR(start_date)=YEAR(NOW()) AND MONTH(start_date)=MONTH(NOW()) AND user_id=3185
        group by YEAR(NOW()),MONTH(NOW())