计算最近12个月的行数 - PHP SQL

时间:2012-03-05 21:19:27

标签: php sql count

我正在尝试计算表格详细信息中的行数,列数(id)并显示最近12个月 - 理想情况下这将是一个滚动的12个月,因此它将显示当前月份和之前的11个月。我有以下但没有返回任何内容:

    $sql = "SELECT DATE_FORMAT(date, '%m') as 'month',
COUNT(id) as 'total'
FROM details
GROUP BY DATE_FORMAT(date, '%m')
";
$result = mysql_query($sql, $con);

if (!$result) {
    echo "DB Error, could not query the database\n";
    echo 'MySQL Error: ' . mysql_error();
    exit;
}

while ($row = mysql_fetch_assoc($result)) {
    $row['month']. " = " .$row['total']. "<br />";
    }

我希望我已经解释过自己,如果没有,请问我......

感谢您的光临。

1 个答案:

答案 0 :(得分:0)

如果您使用的是mssql,请尝试以下查询:

SELECT
    DATEADD(MM, DATEDIFF(MM, 0, date), 0) AS 'month',
    COUNT(1) as 'total'
FROM
    details
WHERE
    date >= DATEADD(MM, DATEDIFF(MM, 0, date) - 12, 0)
GROUP BY
    DATEADD(MM, DATEDIFF(MM, 0, date), 0)

对于MySQL(从MySQL: Query to get all rows from previous month扩展而来),请使用以下WHERE子句

SELECT
    DATE_FORMAT(date, '%m') as 'month',
    COUNT(id) as 'total'
FROM
    details
WHERE
    YEAR(date) >= YEAR(CURRENT_DATE - INTERVAL 12 MONTH)
AND MONTH(date) >= MONTH(CURRENT_DATE - INTERVAL 12 MONTH)
GROUP BY
    DATE_FORMAT(date, '%m')