简体   繁体   English

从两个不同的表中获取数据,这些表在 sql server 中只有一个公共列

[英]getting data from two different tables that have only one common column in sql server

My tables are as follows:我的表如下:

Please give me an SQL query to get the expected result set.请给我一个 SQL 查询以获得预期的结果集。

Table1                  
A   B   C   D   E   
1   2   C1  D1  E1  
2   2   C2  D2  E2  
3   2   C3  D3  E3  


Table2                  
A   B   F   G   H   
1   2   F1  G1  H1  
2   2   F2  G2  H2  
3   5   F3  G3  H3  
4   6   F4  G4  H4  

Expected Result :预期结果 :

B   C       D       E       F       G       H
2   C1      D1      E1      NULL    NULL    NULL
2   C2      D2      E2      NULL    NULL    NULL
2   C3      D3      E3      NULL    NULL    NULL
2   NULL    NULL    NULL    F1      G1      H1
2   NULL    NULL    NULL    F2      G2      H2

You need UNION to combine results of two or more queries as below.您需要UNION来组合两个或多个查询的结果,如下所示。 As you have C, D, E in one table and they are not present in another you need to add this columns with NULL values, the same to F, G, H :由于您在一个表中有C, D, E而它们在另一个表中不存在,因此您需要将此列添加为NULL值,与F, G, H

SELECT *
FROM (
    SELECT  B,   
            C,   
            D,   
            E, 
            NULL F, 
            NULL G, 
            NULL H  
    FROM Table1 t1
    UNION
    SELECT  B,  
            NULL C,
            NULL D, 
            NULL E,  
            F,   
            G,   
            H  
    FROM Table2 t2
) t
WHERE B = 2

Output:输出:

B   C       D       E       F       G       H
2   C1      D1      E1      NULL    NULL    NULL
2   C2      D2      E2      NULL    NULL    NULL
2   C3      D3      E3      NULL    NULL    NULL
2   NULL    NULL    NULL    F1      G1      H1
2   NULL    NULL    NULL    F2      G2      H2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何连接两个没有公共列的 SQL 服务器表 - How to join two SQL Server tables which have no common column 如何从不同服务器上的两个 SQL 服务器表中获取常用列名? - How to get common column names from two SQL Server tables on different servers? 我希望 SQL 查询关联两个表数据,其中两个表各只有一列 - I want SQL query to relate two tables data ,where both tables have only one column each 在 SQL 中合并两个表,一个公共列 - Merge two tables in SQL, with one common column SQL查询联接只有两个表的3个表具有公共实体 - SQL Query to join 3 tables with only two tables have common entity 如何将 SQL 服务器中具有不同列标题 map 的表合并到通用描述? - How to merge tables in SQL server that have a different column headers that map to a common description? 将来自两个不同表的一列中的两组数据组合 - Combine two groups of data in one column from two different tables 如何从两个不同的表中获取数据(没有重复记录)?两个表都有共同的价值 - How to fetch data ( without duplicates records ) from two different tables ? where both tables have common value 从SQL Server中的多个表中获取不同的列值 - Getting Different column values from Multiple tables in SQL Server 从SQL Server中的2个表中获取不同的列名称 - getting different column names from 2 tables in sql server
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM