SQL 之间不包括所有查询范围(日期)
Posted
技术标签:
【中文标题】SQL 之间不包括所有查询范围(日期)【英文标题】:SQL between not include all range of query (date) 【发布时间】:2014-09-16 15:25:52 【问题描述】:我有以下结构的表:
我正在尝试获取两个日期之间的分组值,问题是结果不包含日期为 2014-09-05 的行。
这是查询:
SELECT substr(m.date, 1, 10) as my_date, COUNT(m.ID) AS 'NUMBER_OF_ALL_CALLS',
(SELECT COUNT(*) FROM dialed_calls subq WHERE subq.call_result = 'DONE'
AND substr(m.date, 1, 10) = substr(subq.DATE, 1, 10)) as 'RESULT_DONE',
(SELECT COUNT(*) FROM dialed_calls subq WHERE subq.call_result = 'NOT_INTERESTED'
AND substr(m.date, 1, 10) = substr(subq.DATE, 1, 10)) as 'RESULT_NOT_INTERESTED',
(SELECT COUNT(*) FROM dialed_calls subq WHERE subq.call_result = 'NO_APPOINTMENT'
AND substr(m.date, 1, 10) = substr(subq.DATE, 1, 10)) as 'RESULT_NO_APP'
FROM dialed_calls m
WHERE m.date BETWEEN "2014-09-02" AND "2014-09-05"
GROUP BY my_date
如何解决它以包含给定范围的行。
我也想问一下,我该怎么做才能错过 fxp 的日子:
WHERE m.date BETWEEN "2014-09-02" AND "2014-09-10"
结果返回零值的日期?
非常感谢您的帮助。
表结构:
BEGIN TRANSACTION;
CREATE TABLE dialed_calls(Id integer PRIMARY KEY,
'date' datetime,
'called_number' VARCHAR(45),
'call_result' VARCHAR(45),
'call_duration' INT,
'synced' BOOL);
/* Create few records in this table */
INSERT INTO dialed_calls VALUES(1,'2014-09-02 15:54:34+0200',
'800123456', 'NOT_INTERESTED', 10, 0);
INSERT INTO dialed_calls VALUES(2,'2014-09-02 15:56:30+0200',
'800123456', 'NO_APPOINTMENT', 10, 0);
INSERT INTO dialed_calls VALUES(3,'2014-09-02 16:01:49+0200',
'800123456', 'DONE', 9, 0);
INSERT INTO dialed_calls VALUES(4,'2014-09-02 16:03:03+0200',
'800123456', 'NO_APPOINTMENT', 69, 0);
INSERT INTO dialed_calls VALUES(5,'2014-09-02 18:09:34+0200',
'800123456', 'NO_APPOINTMENT', 3, 0);
INSERT INTO dialed_calls VALUES(6,'2014-09-02 18:54:02+0200',
'123456789', 'NO_APPOINTMENT', 89, 0);
INSERT INTO dialed_calls VALUES(7,'2014-09-02 18:55:25+0200',
'123456789', 'NOT_INTERESTED', 89, 0);
INSERT INTO dialed_calls VALUES(8,'2014-09-03 18:36:58+0200',
'123456789', 'DONE', 185, 0);
INSERT INTO dialed_calls VALUES(9,'2014-09-04 18:36:58+0200',
'123456789', 'DONE', 185, 0);
INSERT INTO dialed_calls VALUES(10,'2014-09-05 18:36:58+0200',
'123456789', 'DONE', 185, 0);
COMMIT;
【问题讨论】:
多个问题过于宽泛;单独问第二个问题。 【参考方案1】:如果只指定日期,则时间默认为 00:00:00。如果将 23:59:59 添加到结束日期,则应该得到完整的日期范围。
【讨论】:
【参考方案2】:x BETWEEN a AND B
只是x >= a AND x <= b
的简写。
如果您不希望 <=
运算符用于第二次比较,请手动将其写出来,然后更改它以便在第二天之前获得任何值:
... WHERE m.date >= '2014-09-02' AND m.date < '2014-09-06'
【讨论】:
【参考方案3】:包含给定范围变化的行
WHERE m.date BETWEEN "2014-09-02" AND "2014-09-05"
为
WHERE substr(m.date, 1, 10) BETWEEN '2014-09-02' AND '2014-09-05'
【讨论】:
以上是关于SQL 之间不包括所有查询范围(日期)的主要内容,如果未能解决你的问题,请参考以下文章