【问题标题】:I'm trying to get the Diff of two fields using SQL我正在尝试使用 SQL 获取两个字段的差异
【发布时间】:2022-01-23 19:20:25
【问题描述】:

我正在尝试使用 SQL 来区分两个字段,但我的字段数据类型之一是文本,另一个是日期。文本字段也采用 UTC 格式,日期字段采用山区标准时间格式。

  1. extract_date 是日期字段。
  2. src_msg_date_time 是文本字段

当我在查询下方运行时,查询工作室中出现“自动化错误”。任何帮助请我做错了什么。!

SELECT
A.extract_date AT TIME ZONE 'Mountain Standard Time' AT TIME ZONE 'UTC' AS EventDate,
B.SmsStandardStatusCode,
B.Description,
A.src_msg_date_time,
A.SubID
FROM
[SmsSendLog] A WITH(NOLOCK)
JOIN
[CustomDataView] B WITH(NOLOCK)
ON A.subid=B.SUBSCRIBERID and a.smsjobid=b.SMSJOBID and a.smsbatchid=b.smsbatchid
where DATEDIFF(Day,A.extract_date,GETDATE()) between 0 and 5
and 
DATEDIFF(hour,(Convert(Datetime, A.src_msg_date_time,120) AT TIME ZONE 'Mountain Standard Time' AT TIME ZONE 'UTC'),(A.extract_date AT TIME ZONE 'Mountain Standard Time' AT TIME ZONE 'UTC')) between 0 and 2

【问题讨论】:

标签: sql tsql automation salesforce-marketing-cloud


【解决方案1】:

t-sql 中不允许从文本到日期时间的显式转换,您可能需要进行双重转换或转换:

SELECT
A.extract_date AT TIME ZONE 'Mountain Standard Time' AT TIME ZONE 'UTC' AS EventDate,
B.SmsStandardStatusCode,
B.Description,
A.src_msg_date_time,
A.SubID
FROM
[SmsSendLog] A WITH(NOLOCK)
JOIN
[CustomDataView] B WITH(NOLOCK)
ON A.subid=B.SUBSCRIBERID and a.smsjobid=b.SMSJOBID and a.smsbatchid=b.smsbatchid
where DATEDIFF(Day,A.extract_date,GETDATE()) between 0 and 5
and 
DATEDIFF(hour,(Convert(Datetime, cast(A.src_msg_date_time as varchar(max)),120) AT TIME ZONE 'Mountain Standard Time' AT TIME ZONE 'UTC'),(A.extract_date AT TIME ZONE 'Mountain Standard Time' AT TIME ZONE 'UTC')) between 0 and 2

参考:

https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver15

【讨论】:

    【解决方案2】:

    我会在子查询中进行时区转换以简化 where 子句。

    SELECT
      sl.extract_date EventDate
    , dv.SmsStandardStatusCode
    , dv.Description
    , sl.src_msg_date_time
    , sl.SubID
    FROM (
       select 
         Convert(Datetime, sl0.src_msg_date_time,120) AT TIME ZONE 'UTC' as src_msg_date_time
       , sl0.extract_date AT TIME ZONE 'UTC' as extract_date
       , convert(date, getDate()) AT TIME ZONE 'UTC' as today
       , sl0.subid
       from SmsSendLog sl0 
    ) sl 
    inner join CustomDataView dv ON sl.subid = dv.SUBSCRIBERID and sl.smsjobid = dv.SMSJOBID and sl.smsbatchid = dv.smsbatchid
    where 
    sl.subid is not null
    and sl.src_msg_date_time is not null
    and sl.extract_date is not null
    and sl.extract_date >= convert(date, sl.today-5) 
    and datediff(hour,sl.src_msg_date_time,sl.extract_date) between 0 and 2
    

    还有:

    • SFMC 中不需要with (nolock)。您对平台中的查询没有这种级别的控制。
    • 在您未来的 SQL 查询问题中,请包含所选数据的样本和所需的输出。当任何数据类型转换和计算是查询的一部分时,这一点尤其重要。

    【讨论】:

      猜你喜欢
      • 2020-08-12
      • 1970-01-01
      • 1970-01-01
      • 2022-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多