SELECT
  nickname,
  team,
  total total_visits,
  doneTotal total_visits_done
FROM (
  SELECT
    userId,
    nickname,
    team,
    MIN(fromDate) fromDate,
    MAX(toDate) toDate,
    COUNT(visitId) total,
    SUM(visitIsDone) doneTotal,
    SUM(planned) plTotal,
    SUM(IF(planned > 0, visitIsDone, 0)) plDone,
    SUM(IF(planned = 0, visitIsDone, 0)) unplDone
  FROM (
    SELECT
      MAX(visitDate) toDate,
      MIN(visitDate) fromDate,
      MIN(mobileUser.userId) userId,
      MIN(mobileUser.tags) team,
      MIN(mobileUser.nickname) nickname,
      IF(MIN(isUnplanned), 0, 1) planned,
      visitId,
      IF(SUM(IF(IFNULL(tasks.actualTimeSeconds, 0) > 0, 1, 0)) > 0, 1, 0) AS visitIsDone
    FROM
      FLATTEN([visitbasis1:archive_11111.visits], tasks)
    WHERE
      visitDate BETWEEN ${date_from_YYYYMMDD}
      AND ${date_to_YYYYMMDD}
    GROUP BY
      visitId )
  GROUP BY
    userId,
    nickname,
    team)
ORDER BY
  nickname,
  team




