外连接返回连接列的多个副本

时间:2017-09-17 20:05:57

标签: sql-server sql-server-2008 pymssql

当我在mssql上执行outer join时,我加入的列不会合并。

这是我的代码:

select top 10 *  from customer_behaviour_1P2014  full outer join
customer_behaviour_2P2014 on customer_behaviour_1P2014.customer_identifier = customer_behaviour_2P2014.customer_identifier full outer join
customer_behaviour_3P2014 on customer_behaviour_2P2014.customer_identifier = customer_behaviour_3P2014.customer_identifier

这将返回标记为customer_identifier的3列,而不是1。

我做错了什么?

如果它有任何区别,我在每个表中都将客户标识符作为索引。

1 个答案:

答案 0 :(得分:2)

您正在从所有3个表中选择所有列,每个表都有一个customer_identifier列(从ON子句推导出来)。

结果中的每个customer_identifier列来自不同的表。匹配时值相同,或者没有行匹配时NULL

指定显式列列表而不是*以避免重复这些值。使用customer_identifier函数返回第一个非NULL值,而不是3个单独的COALESCE列:

SELECT <other-columns>,
COALESCE(customer_behaviour_1P2014.customer_identifier, customer_behaviour_2P2014.customer_identifier, customer_behaviour_3P2014.customer_identifier) AS customer_identifier
FROM ...
相关问题