SELECT
    CD.cloud_date AS event_day,
    IFNULL( event_count, 0) AS event_count,
    IFNULL(error_count, 0) AS error_count
FROM
    cloud_date_table CD
        LEFT JOIN
    (
        SELECT
            evt.event_date ,
            COUNT(evt.event_id) AS event_count,
            SUM(evt.error_event) AS error_count
        FROM
            (
                SELECT
                    (
                        CASE
                            WHEN (:shiftstartgroupingparam) THEN date(date_add(CO.shift_start, interval (-:daystartparam) second))
                            ELSE date(date_add(CO.event_time, interval (CO.event_time_zone - :daystartparam) second))
                            END) AS event_date,
                    CO.event_id,
                    (CO.event_type <2 AND CI.event_id IS NULL AND COUT.event_id IS NULL) AS error_event
                FROM
                    eventlog CO
                        INNER JOIN person P
                                   ON
                                           CO.person_id = P.person_id
                        :GROUP_JOIN

                        LEFT JOIN task T ON CO.task_id = T.task_id LEFT JOIN eventlog CI ON CO.event_id = CI.next_event  LEFT JOIN eventlog COUT ON CO.next_event = COUT.event_id  WHERE CO.is_deleted = 0
                                                                                                                                                                                     AND
                        P.is_deleted = 0
                                                                                                                                                                                     AND
                        P.customer_id= :customerparam

                        :PERSON_FILTER

                        :GROUP_FILTER


                        :TASK_FILTER
                                                                                                                                                                                     AND
                    DATE_ADD((
                        CASE
                            WHEN (:shiftstartgroupingparam) THEN
                                CO.shift_start
                            ELSE date_add(CO.event_time, interval CO.event_time_zone second)
                            END), INTERVAL :daystartparam SECOND) BETWEEN :fromparam
                        AND
                        :toparam
            )
                AS evt
        GROUP BY
            evt.event_date) AS e
    ON
    DATE(CD.cloud_date) = e.event_date
WHERE
    CD.cloud_date BETWEEN :fromparam
  AND :toparam
ORDER BY
    CD.cloud_date