简体   繁体   English

SQL Query中的DateTime转换和比较

[英]DateTime conversion and comparison in SQL Query

I have a sql query for pulling a report from a table.我有一个用于从表中提取报告的 sql 查询。 The idea is to pull the sum of counts, grouped by day of the week, in the local timezone.这个想法是在当地时区提取按星期几分组的计数总和。 Dates in the table are stored in UTC.表中的日期以 UTC 存储。

SELECT (SUM(t.di1) + SUM(t.di2) + SUM(t.di3) + SUM(t.di4)) AS [ScanCount],
       DATEPART(WEEKDAY, t.LocalTime) AS [weekday]
FROM (SELECT di1,
             di2,
             di3,
             di4,
             CreatedOnUTC AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time' AS LocalTime
      FROM tableName
      WHERE DeviceId = 649754) t
WHERE t.LocalTime > '03/16/2020 00:00'
  AND t.LocalTime < '03/16/2020 23:59:59'
GROUP BY DATEPART(WEEKDAY, t.LocalTime)
ORDER BY DATEPART(WEEKDAY, t.LocalTime);

A query like this should only return a single day of the week count, but it returns 2 days.像这样的查询应该只返回一周中的一天计数,但它返回 2 天。 This obviously has something to do with the difference in time zones, whereas the UTC time contains dates from both 3/15 and 3/16.这显然与时区的差异有关,而 UTC 时间包含 3/15 和 3/16 的日期。 It seems that the conversion from UTC to Pacific Time works in the output but the UTC values are used in the where clause.从 UTC 到太平洋时间的转换似乎在输出中起作用,但在 where 子句中使用了 UTC 值。 How can I do this comparison to the new converted datetimes and not to the original UTC times?如何与新转换的日期时间而不是原始 UTC 时间进行比较?

Comparison between datetimeoffset and string literal works in UTC. datetimeoffset 和字符串文字之间的比较在 UTC 中有效。
Simplest solution will be to convert datetimeoffset to datetime2.最简单的解决方案是将 datetimeoffset 转换为 datetime2。 Modify your inner query to:将您的内部查询修改为:

cast(CreatedOnUTC AT TIME ZONE 'UTC' AT TIME ZONE 'Pacific Standard Time' as datetime2(0)) AS LocalTime

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

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