我有一个查询,我试图找出在数据库的某个时间范围内查看某些内容的次数。
到目前为止,这是我的查询:
USE DB1
SELECT DISTINCT NAME,
COUNT(*) AS COUNT
FROM LOGS
WHERE EVENT = 'Viewed'
AND TIME BETWEEN '2015-04-22 00:00:00.000' AND '2015-07-24 00:00:00.000'
GROUP BY NAME
ORDER BY COUNT DESC;
此查询成功告诉我在该3个月范围内查看了多少次,但是当我将时间范围缩短为三个不同的查询时,该特定行更改为:
TIME BETWEEN '2015-04-22 00:00:00.000' AND '2015-05-22 00:00:00.000';
TIME BETWEEN '2015-05-22 00:00:00.000' AND '2015-06-22 00:00:00.000';
TIME BETWEEN '2015-06-22 00:00:00.000' AND '2015-04-24 00:00:00.000';
然后,当我加上不同的值时,它们并不相等。实际上,它们比我在三个月范围内的第一个查询获得的行数要高得多。我假设某些值重叠。我怎么能绕过这个?我已经检查了我的工作,我很确定第一个查询在时间范围内给出了正确的行数,但我需要更具体的数据
答案 0 :(得分:0)
col BETWEEN a AND b
计算为a <= col <= b
,因此您的时间范围内存在重叠间隔
将其从午夜改为午夜之前的一秒:
TIME BETWEEN '2015-04-22 00:00:00.000' AND '2015-04-22 23:59:59.999';
TIME BETWEEN '2015-05-22 00:00:00.000' AND '2015-05-22 23:59:59.999';
TIME BETWEEN '2015-06-22 00:00:00.000' AND '2015-04-24 23:59:59.999';
<强>更新强>
试试这个:
TIME BETWEEN '2015-04-22 00:00:00' AND '2015-04-22 23:59:59';
TIME BETWEEN '2015-05-22 00:00:00' AND '2015-05-22 23:59:59';
TIME BETWEEN '2015-06-22 00:00:00' AND '2015-04-24 23:59:59';
答案 1 :(得分:0)
X BETWEEN Y AND Z
转换为
X >= Y AND X <= Z
因此,您应该对整个范围内的句点使用不同的查询,例如:
TIME >= '2015-04-22 00:00:00.000' AND TIME < '2015-05-22 00:00:00.000';
TIME >= '2015-05-22 00:00:00.000' AND TIME < '2015-06-22 00:00:00.000';
TIME >= '2015-06-22 00:00:00.000' AND TIME <= '2015-07-24 00:00:00.000';
上一段时间的逻辑取决于你...你可以将其重新排列为:
TIME >= '2015-06-22 00:00:00.000' AND TIME < '2015-07-25 00:00:01.000';