[英]Hive query to return single row based on eff and exp date
我有一張包含以下數據的表格。
我期望需要返回的行是 exp_dt“2020-09-22”。 但是當在查詢下面運行時,它返回兩行。 我不明白為什么它在具有 eff_dt“2020-09-19”時也返回第一行。
select id,cd,eff_dt,exp_dt,post_dt from table
where from_unixtime(unix_timestamp(eff_dt,"yyyy-MM-dd")) <= from_unixtime(unix_timestamp("2020-09-21","yyyy-MM-dd"))
and from_unixtime(unix_timestamp(exp_dt,"yyyy-MM-dd")) >= from_unixtime(unix_timestamp("2020-09-21","yyyy-MM-dd"));
我的查詢有問題嗎? 我期待返回第二行。
使用<
與exp_date
進行比較:
select id,cd,eff_dt,exp_dt,post_dt
from table
where from_unixtime(unix_timestamp('2020-09-21', 'yyyy-MM-dd')) >= from_unixtime(unix_timestamp(eff_dt, 'yyyy-MM-dd')) and
from_unixtime(unix_timestamp('2020-09-22', 'yyyy-MM-dd')) < from_unixtime(unix_timestamp(exp_dt, 'yyyy-MM-dd'))
我顛倒了比較順序。 我發現首先遵循常量的邏輯更容易。
這是否捕獲了同一天到期的邊緣情況並同時解決了您的問題?
select id,cd,eff_dt,exp_dt,post_dt from table
where
(from_unixtime(unix_timestamp(eff_dt,"yyyy-MM-dd")) <= from_unixtime(unix_timestamp("2020-09-21","yyyy-MM-dd"))
and
from_unixtime(unix_timestamp(exp_dt,"yyyy-MM-dd")) > from_unixtime(unix_timestamp("2020-09-21","yyyy-MM-dd"))
)
or
(from_unixtime(unix_timestamp(eff_dt,"yyyy-MM-dd")) = from_unixtime(unix_timestamp("2020-09-21","yyyy-MM-dd"))
and
from_unixtime(unix_timestamp(exp_dt,"yyyy-MM-dd")) = from_unixtime(unix_timestamp("2020-09-21","yyyy-MM-dd"))
)
;
事實上,我懷疑 exp 總是 >= eff,所以可能只有一個條件
from_unixtime(unix_timestamp(eff_dt,"yyyy-MM-dd")) <= from_unixtime(unix_timestamp("2020-09-21","yyyy-MM-dd"))
足夠...?
您不需要 from_unixtime(unix_timestamp()) 因為日期已經采用正確的格式並且參數采用相同的 yyyy-MM-dd 格式。
您查詢中的問題是您對 eff 和 exp 日期都使用 equal 要查找日期的最新記錄,請使用此查詢:
select id,cd,eff_dt,exp_dt,post_dt from table
where eff_dt <= "2020-09-21"
and exp_dt > "2020-09-21";
如果你只有日期(沒有時間成分),當 SCD2 中的 eff_dt = exp_dt 時,應該沒有記錄。 僅當您使用時間戳並且時間不同時,日期才能相等,在這種情況下,在檢查之前將您的參數日期轉換為時間戳。
SCD2 的設計方式應使事實記錄可以恰好映射到 SCD2 的一條記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.