【发布时间】:2017-01-20 11:37:49
【问题描述】:
我有这两张桌子
#TABLE1#
##CompanyName## ##PrimaryKey##
DELL 1
DELL CALIFORNIA 2
DELL SAN FRANCISCO 3
DELL LOS ANGELES 4
IBM 5
GOOGLE 6
#TABLE2#
##ParentComp## ##ParentPrimaryKey## ##ChildComp## ##ChildPrimaryKey##
DELL 1 DELL CALIFORNIA 2
DELL CALIFORNIA 2 DELL SAN FRANCISCO 3
DELL CALIFORNIA 2 DELL LOS ANGELES 4
现在预期的表格如下所示;关系(层次结构)列只有三个可能的值(父/子/独立),如图所示:
#TABLE3#
##CompanyName## ##Relationship## ##ParentCompany##
DELL PARENT ---
DELL CALIFORNIA CHILD DELL
DELL SAN FRANCISCO CHILD DELL CALIFORNIA
DELL LOS ANGELES CHILD DELL CALIFORNIA
IBM INDEPENDENT ---
GOOGLE INDEPENDENT ---
我已经尝试了以下两个加入选项
选择
...
表1
左外连接
Table2 ON Table1.PrimaryKey = Table2.ParentPrimaryKey
左外连接
Table2 tAlias2
Table2.ParentPrimaryKey = tAlias2.ChildPrimaryKey
返回
##CompanyName## ##Relationship## ##ParentCompany##
DELL PARENT ---
DELL CALIFORNIA CHILD DELL
DELL SAN FRANCISCO INDEPENDENT ---
DELL LOS ANGELES INDEPENDENT ---
IBM INDEPENDENT ---
GOOGLE INDEPENDENT ---
或
选择
...
表1
左外连接
Table2 ON Table1.PrimaryKey = Table2.ChildPrimaryKey
左外连接
Table1 tAlias1
Table2.ParentPrimaryKey = tAlias1.PrimaryKey
将返回如下内容:
##CompanyName## ##Relationship## ##ParentCompany##
DELL INDEPENDENT ---
DELL CALIFORNIA CHILD DELL
DELL SAN FRANCISCO CHILD DELL CALIFORNIA
DELL LOS ANGELES CHILD DELL CALIFORNIA
IBM INDEPENDENT ---
GOOGLE INDEPENDENT ---
【问题讨论】:
-
Mysql 和 ms sql 是两个不同的产品。请删除不相关的标签。
-
可能类似于
SELECT T.companyName, MAX(COALESCE(T2.relationship, T2A.relationship, 'INDEPENDENT')) relationship, MAX(T2.parentCompany) parentCompany FROM table1 T LEFT JOIN (SELECT 'CHILD', T2.childPrimaryKey, T1.companyName FROM table2 T2 JOIN table1 T1 ON T1.primaryKey = T2.parentPrimaryKey) T2(relationship, childPrimaryKey, parentCompany) ON T2.childPrimaryKey = T.primaryKey LEFT JOIN (SELECT 'PARENT', parentPrimaryKey FROM table2) T2A(relationship, parentPrimaryKey) ON T2A.parentPrimaryKey = T.primaryKey GROUP BY T.companyName;
标签: sql sql-server sql-server-2008 join sql-server-2012