简体   繁体   English

如何使用 WHERE 子句过滤日期和时间范围?

[英]How can I use the WHERE clause to filter a date and range of time?

I'm trying to find customer engagements that occurred at specific date and times,我正在尝试查找在特定日期和时间发生的客户互动,

I think I have the date part correct however I can't seem to set the time right.我想我的日期部分是正确的,但是我似乎无法正确设置时间。

SELECT EngagementNumber,
       StartDate,
       StartTime
FROM Engagements
WHERE StartDate LIKE '2012-10-%%'
      AND StartTime BETWEEN '12:00:00.0000000' AND '17:00:00.0000000';

One reason you have downvotes is because you have chosen to tag your question with 2 databases, but the syntax for each is very different.您投反对票的一个原因是您选择用 2 个数据库标记您的问题,但每个数据库的语法非常不同。

Another is that without some "key facts" we are just left guessing.另一个原因是,如果没有一些“关键事实”,我们只能猜测。 eg what is the datatype of StartTime ??例如what is the datatype of StartTime ?? this is vital to the solution because if data type is DATE then this would fail WHERE StartDate LIKE '2012-10-%%' but if the data type is VARCHAR or similar then it would work (sort of).这对解决方案至关重要,因为如果数据类型是DATE那么这将失败WHERE StartDate LIKE '2012-10-%%'但如果数据类型是VARCHAR或类似,那么它会起作用(有点)。 We also need to know the data type of StartTime.我们还需要知道 StartTime 的数据类型。

So: IF因此,如果

  1. you are using MySQL你正在使用 MySQL
  2. The data type of StartDate is Date StartDate 的数据类型为 Date
  3. The data type of StartTime is Time StartTime 的数据类型是 Time

Below is an example of how your query might work , see a demo at SQL Fiddle下面是您的查询可能如何工作的示例,请参阅SQL Fiddle 上的演示

Sample Data (MySQL) :示例数据(MySQL)

CREATE TABLE Engagements
    (`EngagementNumber` int, `StartDate` datetime, `StartTime` time)
;

INSERT INTO Engagements
    (`EngagementNumber`, `StartDate`, `StartTime`)
VALUES
    (1, '2017-09-01 00:00:00', '13:14:15'),
    (2, '2017-10-01 00:00:00', '14:15:16'),
    (3, '2017-10-11 00:00:00', '15:16:17')
;

Query 1 :查询 1

SELECT EngagementNumber,
       StartDate,
       StartTime
FROM Engagements
WHERE StartDate >= '2017-10-01' and StartDate < '2017-11-01'
AND StartTime BETWEEN '12:00' AND '17:00'

Results :结果

| EngagementNumber |            StartDate | StartTime |
|------------------|----------------------|-----------|
|                2 | 2017-10-01T00:00:00Z |  14:15:16 |
|                3 | 2017-10-11T00:00:00Z |  15:16:17 |

Please note that the same query would also work in SQL Server is the data types are the same as assumed here.请注意,相同的查询也适用于 SQL Server,因为数据类型与此处假设的相同。

A final note.最后一点。 If the data types ARE date & time then they are NOT STRINGS (text) even if they might look like they are.如果数据类型是日期和时间,那么即使它们看起来像,它们也不是字符串(文本)。 So LIKE '2012-10%' will not work but storing date/time information as stings is NOT a good idea anyway.所以 LIKE '2012-10%' 将不起作用,但无论如何将日期/时间信息存储为刺痛都不是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM