如何组合没有常见列字段的两个表?

时间:2014-02-06 09:30:34

标签: sql sql-server sql-server-2008 stored-procedures

  ;WITH K_RT_MasterRetailStoresTable (CommonId,Branch) AS
(
SELECT ROW_NUMBER() OVER(ORDER BY Branch) AS CommonId,Branch
FROM K_RT_MasterRetailStores
 )
 ,K_BR_AddBranchTable (CommonId, branch) AS
 (
SELECT ROW_NUMBER() OVER(ORDER BY branch) AS CommonId,branch
FROM K_BR_AddBranch
 )
 ,K_HM_BranchTable (CommonID,branch) as
(
SELECT ROW_NUMBER() OVER(ORDER BY branch) as CommonId,branch
FROM K_HM_Branch
 )
,k_Master_BranchesTable (CommonID, branch) as
 (
 SELECT ROW_NUMBER() OVER(ORDER BY BRANCH) AS COMMONID,BRANCH
FROM k_Master_Branches
 ) 
  SELECT MRS.BRANCH,AB.BRANCH,B.BRANCH,MB.BRANCH 
  FROM K_RT_MasterRetailStoresTable MR
  LEFT OUTER JOIN K_BR_AddBranchTable AB ON MR.COMMONID = AB.COMMONID 
  LEFT OUTER JOIN K_HM_BranchTable B ON AB.COMMONID = B.COMMONID 
  LEFT OUTER JOIN k_Master_BranchesTable MB ON B.COMMONID = MB.COMMONID

这里显示4列,4个分支数据..但我想显示单列所有分支数据..我可以这样做吗?

2 个答案:

答案 0 :(得分:2)

 ;WITH K_RT_MasterRetailStoresTable (CommonId,Branch) AS
(
SELECT ROW_NUMBER() OVER(ORDER BY Branch) AS CommonId,Branch
FROM K_RT_MasterRetailStores
)
 ,K_BR_AddBranchTable (CommonId, branch) AS
 (
SELECT ROW_NUMBER() OVER(ORDER BY branch) AS CommonId,branch
FROM K_BR_AddBranch
)
 ,K_HM_BranchTable (CommonID,branch) as
(
 SELECT ROW_NUMBER() OVER(ORDER BY branch) as CommonId,branch
FROM K_HM_Branch
)
,k_Master_BranchesTable (CommonID, branch) as
(
SELECT ROW_NUMBER() OVER(ORDER BY BRANCH) AS COMMONID,BRANCH
FROM k_Master_Branches
) 

SELECT distinct BRANCH FROM K_RT_MasterRetailStoresTable
UNION ALL
SELECT distinct BRANCH FROM K_BR_AddBranchTable
UNION ALL
SELECT distinct BRANCH FROM K_HM_BranchTable
UNION ALL
SELECT distinct BRANCH FROM k_Master_BranchesTable;

答案 1 :(得分:1)

不想要并且在下面的陈述中有。

 LEFT OUTER JOIN K_BR_AddBranchTable AB ON MR.COMMONID = AB.COMMONID AND
 LEFT OUTER JOIN K_HM_BranchTable B ON AB.COMMONID = B.COMMONID AND