我正在处理一个数据库,其中日期和时间分为两个单独的列,我的任务是显示两个日期和时间间隔之间的记录。
我做了以下查询,但这只给出了两个日期从10到12的记录。我在第二天12到10之间错过了记录。
我该如何做到这一点?
SELECT
[guid],
[date],
[time],
[pos]
FROM
SomeTable
WHERE
[guid] = '0Q8m48D_uHua6P0'
AND [date] >= '2017-09-12'
AND time >= '10:00'
AND [date] <= '2017-09-13'
AND time <= '12:00';
答案 0 :(得分:1)
您当然可以合并它们,然后使用BETWEEN
进行过滤,如下所示:
SELECT
[guid],
[date],
[time],
[pos]
FROM
SomeTable
WHERE [guid] = '0Q8m48D_uHua6P0'
AND (DATEADD(day, DATEDIFF(day,'19000101', [date]), CAST([time] AS DATETIME2(7)))) BETWEEN '2017-09-12 12:00:00.000' and '2017-09-12 12:00:00.000'
..但这是一个坏主意,因为你的条件有一个函数,将 可能使查询优化器忽略你可能有的任何索引(因为这样的查询不是sargable)
所以,我会在你的桌面上创建一个名为[Datetime]
的新的持久计算列或任何对你有意义的列,然后给它一个默认值:
DATEADD(day, DATEDIFF(day,'19000101', [date]), CAST([time] AS DATETIME2(7))))
然后您可以按如下方式编写查询:
SELECT
[guid],
[date],
[time],
[pos]
FROM
SomeTable
WHERE [guid] = '0Q8m48D_uHua6P0'
AND [Datetime] BETWEEN '2017-09-12 12:00:00.000' and '2017-09-12 12:00:00.000'
答案 1 :(得分:0)
有一个开始和结束日期例外的条款:
SELECT [guid], [date], [time], [pos]
FROM [table]
WHERE [guid] = '0Q8m48D_uHua6P0'
and [date] >= '2017-09-12' AND [time] >= iif([date] = '2017-09-12', '10:00', [time])
AND [date] <= '2017-09-13' AND [time] <= iif([date] = '2017-09-13', '12:00', [time]);
答案 2 :(得分:0)
您可以将列计算为DATETIME
,然后对其进行过滤。
;with cte as (
SELECT
[guid],
[date],
[time],
[pos],
DT = cast([date] as datetime) + cast([time] as datetime)
FROM
SomeTable
WHERE
[guid] = '0Q8m48D_uHua6P0'
)
select *
from cte
where DT between '20170912 10:00' and '20170913 12:00'
答案 3 :(得分:0)
以下是执行此操作的一种方法
SELECT
[guid],
[date],
[time],
[pos]
FROM
SomeTable
WHERE
[guid] = '0Q8m48D_uHua6P0'
AND
CAST (
CONVERT(Varchar(10), [date], 112) + ' ' +
CONVERT(Varchar(8), [time]) AS DateTime) Between '2017-09-12 10:00'
AND '2017-09-13 12:00'