不同的记录按月计算总计

时间:2012-07-31 21:03:44

标签: php sql sql-server

我有一个用户表,我需要在其中运行报告,并显示用户在给定年份中每月输入系统的次数。我创建了一个表,其中第一列返回不同的用户。接下来,在右侧,我想显示每个月输入用户的次数。我目前的代码只统计每个月的总数,并将所有用户的每月总数计算在内。在下面的例子中,每个用户列出5月7日,6月13日,7月12日。但是我希望它能在下面显示它按月分解的情况。

Users    May    June    July  
User1     1       2       3     
User2     1       1       2  
User3     5       10      7   

<?php
$sql = "SELECT record,count(*) as TotalCount,

(select DISTINCT count(*) from Table1 WHERE datereceived BETWEEN '2012-05-01' AND '2012-05-31') as May,
(select DISTINCT count(*) from Table1 WHERE datereceived BETWEEN '2012-06-01' AND '2012-06-30') as June,
(select DISTINCT count(*) from Table1 WHERE datereceived BETWEEN '2012-07-01' AND '2012-07-31') as July
FROM Table1 GROUP BY record";
$params = array();
$options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $sql ,  $params, $options );
if( $stmt === false)
{
echo "Error in query preparation/execution.\n";
die( print_r( sqlsrv_errors(), true));
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) { 
?>  

<tr id="styling">
    <td class="style"><?php echo $row['record']; ?></td>
    <td class="style"><?php echo $row['May']; ?></td>
    <td class="style"><?php echo $row['June']; ?></td>
    <td class="style"><?php echo $row['July']; ?></td>
</tr>
<?php } ?>

2 个答案:

答案 0 :(得分:0)

我认为最好按日期字段进行分组,而不是现在如何使用它。

select DISTINCT count(*) from Table1 GROUP BY EXTRACT(MONTH FROM datereceived)

但我没有看到您使用哪个字段来识别用户。您也可以尝试对该字段进行分组。

答案 1 :(得分:0)

嗨,你可以尝试这个

选择不同的fitstname,datename(month,datereceived),count(*)from 用户按名字,日期名称(月份,日期接收)分组