Моя тестовая таблица:
CREATE TABLE tbl_robbery (
id INTEGER PRIMARY KEY,
city TEXT,
robbert_date DATE
);
Мои тестовые данные:
INSERT INTO tbl_robbery VALUES (1,'Chicago','2017-07-01');
INSERT INTO tbl_robbery VALUES (2,'Chicago','2017-08-01');
INSERT INTO tbl_robbery VALUES (3,'Chicago','2017-08-02');
INSERT INTO tbl_robbery VALUES (4,'Chicago','2017-08-03');
INSERT INTO tbl_robbery VALUES (5,'NY','2017-07-01');
INSERT INTO tbl_robbery VALUES (6,'NY','2017-08-01');
Запрос:
SELECT out.city,
(select count(r2.id) from tbl_robbery r2 WHERE out.city=r2.city GROUP BY r2.city, strftime('%Y-%m',r2.robbert_date) ORDER BY count(r2.id) DESC) as maxcrime,
(select count(r2.id) from tbl_robbery r2 WHERE out.city=r2.city GROUP BY r2.city,strftime('%Y-%m',r2.robbert_date) ORDER BY count(r2.id) ASC) as mincrime,
(select count(r2.id) from tbl_robbery r2 WHERE out.city=r2.city GROUP BY r2.city,strftime('%Y-%m',r2.robbert_date) ORDER BY count(r2.id) DESC)-(select count(r2.id) from tbl_robbery r2 WHERE out.city=r2.city GROUP BY r2.city,r2.robbert_date ORDER BY count(r2.id) ASC) as crime_diff
FROM (select r.city FROM tbl_robbery r GROUP BY r.city) as out
ORDER BY (maxcrime-mincrime) DESC
;
Вывод запроса:
city maxcrime mincrime crime_diff
---------- ---------- ---------- ----------
Chicago 3 1 2
NY 1 1 0