简体   繁体   中英

Using count() to output total entries per month as well as the month

I have tried a bit of searching, and as a result found the count() function to get me closer to my goal, but have stopped a bit. Here's what my code looks like now:

$sql = "SELECT COUNT( * ) as Count
FROM AttendanceDB
WHERE YEAR( class_time ) =  '2015'
AND studentid = '$studentid'
AND furikae = 0
GROUP BY MONTH( class_time )";

Then I use echo $row['Count']; to output the data.

This allows me to total the number of rows per month for the year of 2015 and then output the answer. Now what I want to do is output the month in each row along with the total. I could just preformat everything, but there are some studentids which have entries beginning partway through the year, which means that the first months don't output any results.

How can I SELECT both the month from the DB as well as use the count function at the same time? Thanks

You could use an agregator function

 $sql = "SELECT COUNT( * ),max(YOUR MONTH COLUMN) as MONTH as Count FROM AttendanceDB WHERE YEAR( class_time ) = '2015' AND studentid = '$studentid' AND furikae = 0 GROUP BY MONTH( class_time )"; 

Here is what I think will help you:

$sql = "SELECT MONTH( class_time ) AS month, COUNT( * ) as Count
FROM AttendanceDB
WHERE YEAR( class_time ) =  '2015'
AND studentid = '$studentid'
AND furikae = 0
GROUP BY MONTH( class_time )";

How about:

$sql = "SELECT MONTH(class_time) AS m, COUNT(*) AS c
    FROM AttendanceDB WHERE YEAR(class_time) = '2015'
    AND studentid = '$studentid'
    AND furikae = 0
    GROUP BY m";

This way you'll have the month as a separate column, which will also show in the result as $row['m'] and the count per month as $row['c'] . (I avoid the same names as the MySQL function names, hence the m and c .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM