简体   繁体   English

如何合并来自不同表的具有相同名称但在SQL Server中具有不同值的两列

[英]How to combine two columns from different tables that have a similar name but have different values in SQL Server

I have three tables ( example ) STAFF, STU, EMP . 我有三个表( 示例STAFF, STU, EMP

表

I want to combine the column EMPID in table STAFF and table EMP into 1 column? 我想将表STAFF和表EMP的列EMPID合并为1列?

My previous query is like this, 我以前的查询是这样的,

SELECT *
FROM STU s 
FULL OUTER JOIN STAFF st ON st.STAFFID = STUID 
FULL OUTER JOIN EMP e ON s.STUID = st.EMPID

The result is like this 结果是这样的

结果

The expected result is just like the above screenshot, but I want to join EMPID into one column only. 预期的结果与上面的屏幕截图一样,但是我只想将EMPID加入一列。

UPDATE : 更新

I tried using this query: 我尝试使用此查询:

SELECT 
    stu.stuid, stu.stuname, stu.stucode,
    s.staffid, s.staffname, s.staffcode,
    emp.empname, emp.empcode, 
    COALESCE (emp.empid, staff.staffid) AS col
FROM 
    STU, Staff, EMP 
FULL OUTER JOIN 
    STAFF s ON s.STAFFID = stu.STUID
FULL OUTER JOIN  
    EMP e ON stu.STUID = s.EMPID

but it displays an error like this 但它显示这样的错误

错误

Use below query to get the desired result. 使用以下查询可获得所需的结果。

SELECT s.StuID, s.StuName, s.Stucode, st.StaffId, st.StaffName, st.Staffcode, isnull(st.EmpId, e.EmpId) EmpId, e.EmpCode, e.EmpName
FROM STU s FULL outer JOIN
     STAFF st
     ON st.STAFFID = STUID FULL OUTER JOIN
     EMP e
     ON s.STUID = st.EMPID

Note: You will get the one emp Id column as needed. 注意:您将根据需要获得一个emp Id列。 If Staff emp id is not null then staff emp id will be displayed else employee emp id will be displayed 如果职员emp id不为null,则将显示职员emp id,否则将显示职员emp id

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

相关问题 合并具有相同列和不同值的两个表的最佳方法 - best way to combine two tables that have same columns and different values Sql 服务器如何在具有不同后缀的不同表中查找值 - Sql Server how to find values in different tables that have different suffix 如果两个不同表中的两个相同列具有值,如何返回true? 的SQL - How to return true if two same columns in two different tables have values? SQL 连接来自两个不同表的两个列,其中两个列都有部分相似的数据 - Join two columns from two different tables where both the columns have partially similar data SQL Server:如何查找列具有不同值的ID - SQL Server : how to find ids where columns have different values 如何在SQL Server中合并两个表,这些表包含不同的列名但包含相似的信息 - How to combine two tables in Sql Server which contains different column names but holds similar information 连接具有相似列但不同值的两个表 - Joining two tables with similar columns but different values 如何将两个不同的表与不同的列组合 - How to combine two different tables with different columns 如何从不同的表SQL Server添加两个字符串列? - How to add two string columns from different tables SQL Server? 查找与不同列具有相似值的行 - find rows that have similar values to different columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM