SELECT
    COUNT(*) AS `count`,
    date_format(attendances.att_date, "%%Y-%%m") AS `month`
FROM
    attendances
    JOIN
        (
            SELECT
                *
            FROM
                placements
            WHERE
                placements.classroom_id IN(%s)
        ) pl
    ON  pl.jidou_id = attendances.jidou_id
    AND date_format(attendances.att_date, "%%Y%%m") BETWEEN pl.startmonth AND pl.endmonth
    LEFT JOIN
        absence_reasons
    ON  attendances.absence_reason = absence_reasons.id
    LEFT JOIN
        calendar
    ON  attendances.att_date = calendar.date
WHERE
    attendances.att_date BETWEEN "%s" AND "%s" %s
AND (
        calendar.attendance_preference = 1
    OR  (
            calendar.attendance_preference IS NULL
        AND DAYOFWEEK(attendances.att_date) != 1
        AND attendances.att_date NOT IN(%s)
        )
    )
AND ((
            (
                attendances.enter_time != ""
            OR  attendances.leave_time != ""
            )
        AND (
                attendances.absence IS NULL
            OR  attendances.absence != 1
            )
        ) %s) %s
GROUP BY
    date_format(attendances.att_date, "%%Y-%%m")
;