I have a table of users where I need to run a report and show how many times the users were entered into the system for each month in a given year. I have created a table where the first column returns the distinct users. Next, to the right, I want to show how many times the user was entered for each month. The code I currently has only counts the totals for each month and puts the totals in every month for all users. In the case below it lists 7 for May, 13 for June, and 12 for July for every user. But I want it to show like below where it breaks it down by month.
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.
";
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 } ?>
I think it's better to group by your date field instead of how you use it now.
select DISTINCT count(*) from Table1 GROUP BY EXTRACT(MONTH FROM datereceived)
But i don't see which field you use to identify a user. You can try to group on that field as wel.
hi you can try this one
select distinct fitstname, datename(month,datereceived), count(*) from users group by firstname, datename(month,datereceived)