Teradata中的日期差异

时间:2017-06-18 23:42:28

标签: sql date teradata

我正在尝试在两个dim_ck字段之间进行日期差异。如果是< 30,那么我需要设置标记Y,否则设置N

遵循的步骤:

因为它是dim_ck,我将其从Date转换为dim_ck-3有一个值,因此我不允许转换,因此我尝试将默认日期设置为-3,然后将其转换为Date。以下查询返回YN会导致Terdata数据库,但它没有正确地获取日期差异。

对于例如1998/07/31 - 2015/10/01 = Y,它实际上是> 30,因此它应该返回N。请帮忙。

查询:

SELECT date_dim_ck, 
   end_date_dim_ck, 
   CASE 
     WHEN( CASE 
       WHEN date_dim_ck = -3 THEN (To_date('01/01/1753', 'mm/dd/yyyy')) 
          ELSE Cast(( date_dim_ck - 19000000 ) AS DATE) 
     END - ( Cast (( end_date_dim_ck - 19000000 ) AS DATE) ) ) < 30 
     THEN 'Y' 
       ELSE 'N' 
     END AS FLAG 
   FROM table 

1 个答案:

答案 0 :(得分:1)

#1:您没有正确转换SQL Server的DATEDIFF (day, date_dim_ck, end_date_dim_ck)

SELECT DATE '1998-07-31' - DATE '2015-10-01'返回-6217,小于30: - )

#2:无需应用TO_DATE加上格式,Teradata支持标准SQL日期文字DATE 'YYYY-MM-DD'

CASE 
  WHEN Cast (( end_date_dim_ck - 19000000 ) AS DATE)  -   
    CASE 
      WHEN date_dim_ck = -3
        THEN DATE '1753-01-01'
        ELSE Cast(( date_dim_ck - 19000000 ) AS DATE) 
    END < 30 
  THEN 'Y' 
    ELSE 'N' 
END AS FLAG 

假设数据中实际上不存在1753-01-01:

CASE 
  WHEN Cast ((end_date_dim_ck - 19000000 ) AS DATE)
     - Cast((NullIf(date_dim_ck,-3) - 19000000 ) AS DATE) < 30 
  THEN 'Y' 
  ELSE 'N' 
END AS FLAG

顺便说一句,Teradat支持的最低日期是DATE '0001-01-01'