[英]Apply Mapping of Key-Value pair in Snowflake SQL
我有这张表:
Table_1:
KeyValue, Month
1, Oct,
3, Nov,
4, Sep,
5, Jan
直到“十二月”。 我希望这个故事用作另一个表查询的字典。 所以,如果我给出一个案例查询,我得到的日期比这个月的月份应该被 Table_1 的 KeyValue 替换。 例如:
CAST(Month(getdate()) as int)
gives "Sep" but the output should be
"4" because it is KeyValues of 'Sep' in Table_1
在雪花中如何实现?
它只是一个在字典表中查找的子查询:
SELECT *, (SELECT t1.KeyValue FROM Table_1 AS t1 WHERE t1.Month = MONTH(GETDATE()))
FROM some_tab;
也可以实现为 JOIN:
SELECT s.*, t1.KeyValue
FROM some_tab AS s
JOIN Table_1 AS t1
ON t1.Month = s.<col_name>;
当您可以通过简单的连接来实现它时,我试图了解这里的复杂性。
month_mapping
视为您的具有键值对的映射表,并将dataset
视为您要加入的另一个表
with month_mapping (month_key, month_value) as
(
select * from
(
values (1, 'Oct')
, (3, 'Nov')
, (4, 'Sep')
, (5, 'Jan')
)
)
, dataset (actual_date) as
(
select * from
values (current_timestamp)
, (dateadd(month, 1, current_timestamp))
, (dateadd(month, 2, current_timestamp))
, (dateadd(month, 4, current_timestamp))
, (dateadd(day, 2, current_timestamp))
, (dateadd(day, -10, current_timestamp))
, (dateadd(day, 20, current_timestamp))
)
select ds.actual_date, mm.month_key, mm.month_value
from dataset ds
inner join month_mapping mm
on upper(mm.month_value) = upper(monthname(ds.actual_date))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.