【问题标题】:Unique table from multiple ones having same and different columns (SQL)来自多个具有相同和不同列的唯一表 (SQL)
【发布时间】:2022-01-12 03:44:33
【问题描述】:

我有多个具有不同行和字段的数据集。

dataset1
Customer_ID   Date       Category Address         City          School
4154124       1/2/2021      A      balboa st.    Canterbury   Middleton
2145124       1/2/2012      A      somewhere     world        St. Augustine
1621573       1/2/2012      A      my_street     somewhere    St. Augustine



dataset2
Customer_ID   Date           Category Country  Zipcode   
14123         12/12/2020        B       UK      EW
416412        14/12/2020        B       ES      


dataset3
Customer_ID   Date          Category School         University 
4124123       07/12/2020       C       Middleton      Oxford

我想要一个包含所有列的最终数据集(只保留一个普通列的副本):

Customer_ID   Date       Category Address         City          School  Country  Zipcode  University
    4154124       1/2/2021      A      balboa st.    Canterbury   Middleton
    2145124       1/2/2012      A      somewhere     world        St. Augustine
    1621573       1/2/2012      A      my_street     somewhere    St. Augustine
    14123         12/12/2020        B                                    UK      EW
    416412        14/12/2020        B                                    ES      
    4124123       07/12/2020       C                            Middleton                   Oxford

左连接是获得预期输出的最佳方式吗?如何只保留 Customer_ID 日期和类别以及重复列(例如学校)一次?

【问题讨论】:

    标签: sql teradata-sql-assistant


    【解决方案1】:

    您可以使用 UNION ALL 实现此目的。

    SELECT Customer_ID, Date, Category, Address, City, School, '' AS Country, '' AS ZipCode, '' AS university  FROM dataset1 
    UNION ALL
    SELECT Customer_ID, Date, Category, '', '', '', Country, Zipcode, ''   FROM dataset2
    UNION ALL
    SELECT Customer_ID, Date, Category, '', '', School, '', '', University FROM dataset3
    

    【讨论】:

    • 不清楚您在后​​端查询哪个数据库。如果是 Teradata (Vantage),那么您应该在第一个 SELECT 中显式 CAST 值(至少是常量)以获得数据类型和大小需要保持最终结果。其他一些数据库可能会默认或自动调整每列的结果类型,但 Teradata 不会。
    猜你喜欢
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2017-06-12
    • 1970-01-01
    • 2021-06-25
    相关资源
    最近更新 更多