【问题标题】:Returning records between 2 timestamps返回 2 个时间戳之间的记录
【发布时间】:2022-11-12 12:51:09
【问题描述】:

我想过滤我的结果以仅返回 2 个时间变量之间的记录。在此示例中,我只想要 time_stamp_local 介于 13:00:00 和 14:00:00 之间的结果。我的 WHERE 语句有问题。请协助。

declare @dateFrom date = '2022-09-01'
declare @dateTo date   = '2022-09-30'
declare @TimeFrom time(0) = '13:00:00'
declare @TimeTo time(0) = '14:00:00'
 
select T.external_id as Stop_ID,PC2.time_stamp_local,isnull(sum([in]),0) as Boarding_Passengers,isnull(sum([out]),0) as Alighting_Passengers,
T.LineName as Line, CAST(PC2.time_stamp_local as time(0)) as Time, CAST(Convert(varchar,@TimeFrom) as time(0)) as FROM_
from
(
select sp.external_id,sp.descr,sp.stop_point_id,L.line_id,L.descr as LineName
from apt..apt_calendar C
       INNER join apt..apt_journey_in_block JIB on C.network_ver_id = JIB.network_ver_id and C.period_id = JIB.period_id
       INNER join apt..apt_journey J on JIB.network_ver_id = J.network_ver_id and jib.journey_id = J.journey_id
       INNER join apt..apt_line L on C.network_ver_id = L.network_ver_id and J.line_id = L.line_id
       INNER join apt..apt_point_in_journey_pattern PIJP ON J.network_ver_id = PIJP.network_ver_id and J.journey_pattern_id = PIJP.journey_pattern_id
       INNER join apt..apt_stop_point SP on C.network_ver_id = SP.network_ver_id and PIJP.stop_point_id = SP.stop_point_id
where cast(c.calendar_day as date) between @dateFrom and @dateTo and j.company_id like '11%'
group by sp.external_id,sp.descr,sp.stop_point_id,L.line_id,L.descr
) T
LEFT JOIN [I4M].[VS].[vs_passenger_count2] PC2 ON cast(PC2.calendar_day as date) between @dateFrom and @dateTo and PC2.stop_point_id = T.stop_point_id and PC2.line_id = T.line_id
left join  i4m.vs.vs_passenger_count2_door PC2D on PC2.id = PC2D.passengar_count_id and PC2.error_flags = 0
WHERE PC2D.[in] != 0 or PC2D.[out] != 0 and CAST(PC2.time_stamp_local as time(0)) > cast(Convert(varchar,@TimeFrom) AS TIME(0)) 
    and CAST(PC2.time_stamp_local as time(0)) < cast(Convert(varchar,@TimeTo) AS TIME(0))
group by T.external_id,PC2.time_stamp_local,T.LineName,T.line_id--,CAST(PC2.time_stamp_local as time(0))
order by T.LineName

【问题讨论】:

    标签: sql filter time


    【解决方案1】:

    看起来您希望将列转换为 Time,因为转换为 Time(0) 会舍入毫秒,而转换为 Time 会截断毫秒。考虑:

    select getdate(), datediff(MILLISECOND, CAST(getdate() as time),  CAST(getdate() as time(0))) delta
    

    返回

    (No column name)        delta
    2022-11-11 18:54:15.590 410
    

    显示投射到time(0) 的值为18:54:16。试试.. CAST(PC2.time_stamp_local as Time) &lt; @TimeTo..。请注意,您不需要强制转换 @TimeTo 参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-02
      • 1970-01-01
      • 2012-02-02
      • 2015-04-20
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多