如何计算雪花中不同格式的日期差异?

时间:2021-06-03 15:42:09

标签: sql date snowflake-cloud-data-platform

我正在合并 Snowflake 中的 2 个大表,并且我有 2 列(每个表一列):

“Year_birth”和“Exam_date”以及里面的信息分别是这样的:

“1918”和“2007-03-13”(NUMBER(38,0) 和 VARCHAR(256))

  • 我只想合并差异(即考试年龄)为“>18”和“<60”的行
  • 我正在尝试使用 SELECT DATEDIFF(year,Exam_date, Year_birth) 但没有成功。

关于如何在 Snowflake 中实现的任何想法?

干杯!

3 个答案:

答案 0 :(得分:1)

您只有一年,因此对于一年中的特定日期您无能为力——您需要处理近似值。

因此,从日期字符串中提取年份(arggh!它实际上应该是一个 date)并进行比较:

where (left(datestr, 4)::int - yearnum) not between 18 and 60

我强烈建议您修复数据库并使用正确的 date 数据类型存储这些值。

答案 1 :(得分:0)

在执行 datediff 之前,您需要将整数年份转换为日期

示例:

set YearOfBirth = 1918;
set ExamDate = '2007-03-03'::DATE;
-- select $YearofBirth as YearofBirth, $ExamDate as ExamDate;
select $YearofBirth as YearofBirth,($YearofBirth::TEXT||'-01-01')::DATE as YearofBirthDate, $ExamDate as ExamDate, datediff(year,($YearofBirth::TEXT||'-01-01')::DATE,$ExamDate) as YearsSinceExam;

enter image description here

答案 2 :(得分:0)

在 WHERE 子句中使用 YEARS_DIFF 来过滤 18 岁和 60 岁之间的差异 SELECT DATEDIFF( YEAR,'2007-03-03',TO_DATE(2018::CHAR(4),'YYYY')) YEARS_DIFF;