我正在使用sqlite。我有一个数据库表(抢劫案),存储发生抢劫的时间和地点。抢劫表具有以下属性:日期,城市,身份证(PK)。日期是抢劫发生的日期(每一行表示一次抢劫)。
日期以以下格式存储在抢劫表中:2017-07-01
我正在尝试获取以下信息: 在此期间每个月发生的抢劫总和:2016-07至2017-02之间。
例如,从附加的数据库中,我想通过查询获得此结果:
2016-08: 2
2016-09: 1
2017-02: 1
答案 0 :(得分:1)
我相信以下内容可以满足您的要求(为方便起见,日期是不同的,不会添加问题中显示的所有日期):-
SELECT substr(date,1,7)||':' AS Date, count() AS number_of_robberies
FROM robbery
WHERE datetime(date) BETWEEN datetime('2016-01-01') AND datetime('2017-02-28')
GROUP BY substr(datetime(date),1,7)
;
使用以下命令(加载一些数据):-
DROP TABLE IF EXISTS robbery;
CREATE TABLE IF NOT EXISTS robbery (id INTEGER PRIMARY KEY, city TEXT, date TEXT);
INSERT INTO robbery (city,date) VALUES
('Chicago','2018-01-01'),('New York','2017-03-21'),
('Chicago','2018-02-01'),('New York','2018-01-21'),
('Chicago','2018-02-01'),('New York','2018-03-21'),
('Chicago','2018-02-01'),('New York','2017-01-21'),
('Chicago','2018-03-01'),('New York','2018-03-21'),
('Chicago','2018-03-01'),('New York','2018-01-21'),
('Chicago','2018-03-01'),('New York','2017-01-21'),
('Chicago','2016-01-01'),('New York','2017-03-21'),
('Chicago','2018-02-01'),('New York','2018-01-21'),
('Chicago','2017-02-01'),('New York','2018-03-21'),
('Chicago','2018-02-01'),('New York','2016-01-21'),
('Chicago','2016-03-01'),('New York','2016-03-21'),
('Chicago','2016-03-01'),('New York','2018-01-21'),
('Chicago','2018-03-01'),('New York','2018-01-21');
SELECT substr(date,1,7)||':' AS Date, count() AS number_of_robberies
FROM robbery
WHERE datetime(date) BETWEEN datetime('2016-01-01') AND datetime('2017-02-28')
GROUP BY substr(datetime(date),1,7)
;
结果:-