
WITH ALL_INC AS (SELECT
  ID,
  NAME
FROM (SELECT
      ID,
      TYPE ||  SUBSTR('00000000' || NUMBER, -8) || ' - ' ||  NAME AS NAME
    FROM INCIDENT)
ORDER BY NAME),

E AS (SELECT
  IFNULL(INC.NAME, ENT.ID) NAME,
  ENT.DURATION,
  ENT.TIMESTAMP,
  STRFTIME('%w', ENT.TIMESTAMP) AS DOW,
  CASE STRFTIME('%w', ENT.TIMESTAMP) WHEN '0' THEN ENT.DURATION ELSE 0 END AS SUN,
  CASE STRFTIME('%w', ENT.TIMESTAMP) WHEN '1' THEN ENT.DURATION ELSE 0 END AS MON,
  CASE STRFTIME('%w', ENT.TIMESTAMP) WHEN '2' THEN ENT.DURATION ELSE 0 END AS TUE,
  CASE STRFTIME('%w', ENT.TIMESTAMP) WHEN '3' THEN ENT.DURATION ELSE 0 END AS WED,
  CASE STRFTIME('%w', ENT.TIMESTAMP) WHEN '4' THEN ENT.DURATION ELSE 0 END AS THU,
  CASE STRFTIME('%w', ENT.TIMESTAMP) WHEN '5' THEN ENT.DURATION ELSE 0 END AS FRI,
  CASE STRFTIME('%w', ENT.TIMESTAMP) WHEN '6' THEN ENT.DURATION ELSE 0 END AS SAT
FROM ENTRY AS ENT
LEFT JOIN ALL_INC AS INC ON
  ENT.INCIDENT = INC.ID
WHERE
STRFTIME('%Y-%m-%d', ENT.TIMESTAMP) BETWEEN DATE(:startdate) AND DATE(:enddate))

SELECT
  E.NAME,
  printf("%.1f", SUM(E.DURATION) / 60.0) AS TOTALS,
  printf("%.1f", SUM(E.SUN) / 60.0) AS SUN,
  printf("%.1f", SUM(E.MON) / 60.0) AS MON,
  printf("%.1f", SUM(E.TUE) / 60.0) AS TUE,
  printf("%.1f", SUM(E.WED) / 60.0) AS WED,
  printf("%.1f", SUM(E.THU) / 60.0) AS THU,
  printf("%.1f", SUM(E.FRI) / 60.0) AS FRI,
  printf("%.1f", SUM(E.SAT) / 60.0) AS SAT
FROM E
GROUP BY E.NAME
UNION ALL
SELECT
  'TOTAL' AS NAME,
  printf("%.1f", SUM(E.DURATION) / 60.0) AS TOTALS,
  printf("%.1f", SUM(E.SUN) / 60.0) AS SUN,
  printf("%.1f", SUM(E.MON) / 60.0) AS MON,
  printf("%.1f", SUM(E.TUE) / 60.0) AS TUE,
  printf("%.1f", SUM(E.WED) / 60.0) AS WED,
  printf("%.1f", SUM(E.THU) / 60.0) AS THU,
  printf("%.1f", SUM(E.FRI) / 60.0) AS FRI,
  printf("%.1f", SUM(E.SAT) / 60.0) AS SAT
FROM E
