雪花中的多枢轴问题

时间:2021-03-30 14:22:31

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

无法在 Snowflake 中使用多列透视。单列枢轴工作正常。 以下是我的查询:

SELECT * FROM ( SELECT DISTINCT geo_lkp.MSA_CD , geo_lkp.MSA_NM, geo_lkp.CSA_CD , 
    geo_lkp.CSA_NM
    FROM T_GEO_LKP geo_lkp , T_DIM_STATE_PROV state_lkp 
    WHERE geo_lkp.state_prov_nm = state_lkp.state_prov_cd 
    AND UPPER(geo_lkp.PSTL_CD) = '12345' AND state_lkp.ISO_3_CHAR_CNTRY_CD = 'USA' ) 
    
    UNPIVOT( (LOCATION_CODE, LOCATION_NAME) FOR LOCATION_TYPE
            IN ( (CSA_CD,CSA_NM) AS 'csa', 
                 (MSA_CD,MSA_NM) AS 'msa') )
                ORDER BY LOCATION_NAME 

尝试转换下表数据:

<头>
MSA_CD MSA_NM CSA_CD CSA_NM
10580 奥尔巴尼 104 奥尔巴尼

<头>
LOCATION_TYPE LOCATION_CD LOCATION_NM
msa 10580 奥尔巴尼
csa 104 奥尔巴尼

2 个答案:

答案 0 :(得分:1)

我建议使用横向连接和values

select v.*
from t cross join lateral
     (values ('msa', msa_cd, msa_nm),
             ('csa', csa_cd, csa_nm)
     ) v(location_type, location_cd, location_nm)

         

答案 1 :(得分:0)

从雪花支持中我们了解到目前不支持多列 UNPIVOT。我们必须做一些工作。一个可以是@gordon Linoff 提到的。

另一种解决方案可以是:

with location_data as (
    SELECT DISTINCT geo_lkp.MSA_CD , geo_lkp.MSA_NM, geo_lkp.CSA_CD ,
    geo_lkp.CSA_NM
    FROM T_GEO_LKP geo_lkp , T_DIM_STATE_PROV state_lkp
    WHERE geo_lkp.state_prov_nm = state_lkp.state_prov_cd
    AND UPPER(geo_lkp.PSTL_CD) = '12345' AND state_lkp.ISO_3_CHAR_CNTRY_CD = 'USA' 
    )
select location_type, location_code, location_name from
(
  select 'csa' as location_type, csa_cd as location_code, csa_nm as location_name from location_data
  union all
  select 'msa', msa_cd, msa_nm from location_data
) where location_code is not null order by location_name;