简体   繁体   English

在 Snowflake 中应用键值对映射 SQL

[英]Apply Mapping of Key-Value pair in Snowflake SQL

I have this Table:我有这张表:

Table_1:
KeyValue, Month
 1,      Oct,
 3,      Nov,
 4,      Sep,
 5,      Jan

upto "December".直到“十二月”。 I want this tale to use as dictionary for another table query.我希望这个故事用作另一个表查询的字典。 So, if i am giving a Case query, where i am getting the Month of a date than this month should be replaced by the KeyValue of Table_1.所以,如果我给出一个案例查询,我得到的日期比这个月的月份应该被 Table_1 的 KeyValue 替换。 For example:例如:

CAST(Month(getdate()) as int)

gives "Sep" but the output should be 
 "4" because it is KeyValues of 'Sep' in Table_1

How it can be achieved in Snowflake?在雪花中如何实现?

It is just a subquery that perfrom lookup in dictionary table:它只是一个在字典表中查找的子查询:

SELECT *, (SELECT t1.KeyValue FROM Table_1 AS t1 WHERE t1.Month = MONTH(GETDATE()))
FROM some_tab;

Also possible to implement as JOIN:也可以实现为 JOIN:

SELECT s.*, t1.KeyValue
FROM some_tab AS s
JOIN Table_1 AS t1 
  ON t1.Month = s.<col_name>;

I am trying to understand what is so complex here when you can achieve it with a simple join.当您可以通过简单的连接来实现它时,我试图了解这里的复杂性。

Consider month_mapping as your mapping table with key-value pair, and dataset as another table that you want to join with 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM