【问题标题】:Datediff function in TeraData SQL?TeraData SQL 中的 Datediff 函数?
【发布时间】:2021-12-30 01:35:23
【问题描述】:

我是新来的,有点混乱,所以如果我在这里做错了什么,我会在一开始就原谅自己。

我通常使用 MySQL 或有时使用 Oracle,但现在我必须切换到 Teradata。

我只需要转换这个:

SELECT FLOOR(DATEDIFF(NOW(),`startdate`)/365.25) AS `years`, 
       COUNT(FLOOR(DATEDIFF(NOW(),`startdate`)/365.25)) AS `numberofemployees` 
FROM `employees` 
WHERE 1 
GROUP BY `years` 
ORDER BY `years`; 

进入 teradata。

如果有人能帮忙就好了:)

【问题讨论】:

  • Teradata:只需减去日期:SELECT DATE 'date1' - DATE 'date2';
  • 这是一个大概的年龄计算,(current_date - startdate)/365.25,精确的年龄计算:Cast((Months_Between(Current_Date, startdate) / 12) AS smallint)

标签: sql teradata date-arithmetic


【解决方案1】:

您在 Teradata 中的查询相当于:

SELECT FLOOR((CURRENT_DATE - startdate)/365.2500) AS years, 
       COUNT(FLOOR((CURRENT_DATE - startdate )/365.2500)) AS numberofemployees 
FROM employees
--WHERE 1
GROUP BY years 
ORDER BY years; 

CURRENT_DATE 等同于 NOW() (如果没有时间部分,DATEDIFF 部分无论如何都会忽略它)。 在 Teradata 中,您可以简单地减去日期来获得中间的天数。 另外,我在 365.25 的末尾添加了两个零,以强制 Teradata 将除法计算到小数点后 4 位,因为 MySQL 似乎是这样做的 (https://dev.mysql.com/doc/refman/8.0/en/arithmetic-functions.html#:~:text=In%20division%20performed%20with%20/%2C%20the%20scale%20of%20the%20result%20when%20using%20two%20exact-value%20operands%20is%20the%20scale%20of%20the%20first%20operand%20plus%20the%20value%20of%20the%20div_precision_increment%20system%20variable%20(which%20is%204%20by%20default).

但是,我不确定是否彻底理解了您的原始查询:

  1. WHERE 1 有什么作用?
  2. 为什么要计算 years 列并称其为 numberofemployees(为什么不简单地进行 count(*)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-11
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多