问题描述:

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

网友答案:

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 )";
网友答案:

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 )";
网友答案:

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.)

相关阅读:
Top