﻿update notes set time_stamp = strftime('%s','now') where active;
update notes set active = 0 where id in (select id from notes n join (select type_id, date, count() from notes where active group by type_id, date having count() > 1) d on n.type_id = d.type_id and n.date = d.date join (select type_id, date, min(id) minId from notes group by type_id, date) m on n.type_id = m.type_id and n.date = m.date where n.id > m.minId);
DROP VIEW territories;
CREATE VIEW territories AS SELECT territory_city.city, territory.*, territory_type.type_name, assignedTerritories.person_id, persons.firstname || ' ' || persons.lastname publisher, CASE WHEN workedthrough.elapseddays <= 187 THEN 1 WHEN workedthrough.elapseddays <= 365 THEN 2 WHEN workedthrough.elapseddays > 365 THEN 3 END AS workedthrough, workedthrough.lastworked_date FROM territory LEFT JOIN territory_city ON territory.city_id = territory_city.id LEFT JOIN territory_type ON territory.type_id = territory_type.id LEFT JOIN (SELECT territory_id, person_id FROM territory_assignment WHERE IFNULL(territory_assignment.checkedbackin_date, '') = '' AND territory_assignment.active) assignedTerritories ON territory.id = assignedTerritories.territory_id LEFT JOIN persons ON assignedTerritories.person_id = persons.id LEFT JOIN (SELECT territory_assignment.territory_id, julianday(datetime('now')) - julianday(max(territory_assignment.checkedbackin_date)) AS elapseddays, max(territory_assignment.checkedbackin_date) AS lastworked_date FROM territory_assignment WHERE IFNULL(territory_assignment.checkedbackin_date, '') <> '' AND territory_assignment.active GROUP BY territory_assignment.territory_id) workedthrough ON territory.id = workedthrough.territory_id WHERE (territory_city.active OR territory_city.active IS NULL) AND (territory_type.active OR territory_type.active IS NULL) AND territory.active;
