簡體   English   中英

在 Snowflake 中應用鍵值對映射 SQL

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM