如何从数据库获取最近12个月的记录

时间:2015-12-30 06:48:30

标签: php codeigniter

你好我的问题是如何从数据库中获取最近12个月的记录,如果任何月份没有任何记录,那么它应该将月份值返回为0。 所以如何做到这一点可以帮助我解决这个问题。

我尝试了以下查询,但它只返回那些有记录的月份记录。

$query =  $this->db->select('count(*) as count,MONTHNAME(created_at) as months,MONTH(created_at) as month')
                       ->where('created_at >= DATE_SUB(now(), INTERVAL 12 MONTH)')
                       ->group_by('months')
                       ->order_by('month')
                       ->get('users');

3 个答案:

答案 0 :(得分:0)

SELECT * FROM tbl 
WHERE dt >=DATEADD(month,-12,DATEADD(day,DATEDIFF(day,0,GETDATE()),0)) 
AND dt <=DATEADD(day,DATEDIFF(day,0,GETDATE()),0)

请参阅以下链接:

SQL function for last 12 months

答案 1 :(得分:0)

试试这个..

$query = "SELECT * FROM `tablename` WHERE date > DATE_SUB(NOW(), INTERVAL 12 MONTH) AND `id`='$id'";

答案 2 :(得分:0)

试试这个

# get current Year and month
$currentYear = date("Y");
$currentMonth = date("m");

# set that to filter
$startDate = $currentYear.'01-01'; // output - 2015-01-01
$endDate = $currentYear.'-'.$currentMonth.'-31'; // output - 2015-currentMonth-31

# and your query should be this
$query = $this->db->query(
    "SELECT count(distinct u.id) as monthCount
    FROM users as u
    WHERE created_at >= $startDate 
    AND created_at >= $endDate 
    GROUP BY monthCount
    ");

$result = $query->result_array();
return $result;