如何组合两个选择SQL语句?

时间:2016-12-02 03:36:45

标签: sql sql-server

  Select 
      b.subCusNo, c.companyName as [Subsidiary], b.equityInterest,b.relation
  From  
      cusparentsub b, customerdetails c
  Where 
      b.subcusNo = c.custNo 

  Select  
      b.parentCusNo,c.companyName as [Parent Company], b.equityInterest, b.relation
  From 
      cusparentsub b, customerdetails c
  Where 
      b.parentcusNo = c.custNo

以上是两个SQL语句。是否可以加入select语句,输出将在一个包含subcusno, companyname, parentcusno, companyname, equityinterest和关系数据的表中?

我希望companyname列显示在subcusno列之后和parentcusno之后。两个公司名称数据都来自同一个表。这可能吗?

谢谢

3 个答案:

答案 0 :(得分:1)

您可能希望使用更新的JOIN语法。我使用左连接作为父级,但取决于你真正想要的,你可以使用INNER JOIN

SELECT b.subCusNo,
       c.companyName,
       b.parentCusNo,
       pc.companyName AS [Parent Company],
       b.equityInterest,
       b.relation
FROM cusparentsub b
JOIN customerdetails c ON b.subcusNo = c.custNo
LEFT JOIN customerdetails pc ON b.parentCusNo=pc.subCusNo

答案 1 :(得分:0)

SELECT b.subCusNo, b.parentCusNo,c.companyName as [Subsidiary],   
b.equityInterest,b.relation
FROM cusparentsub b
JOIN customerdetails c ON b.subcusNo = c.custNo 
JOIN customerdetails d ON b.parentcusNo = d.custNo 

答案 2 :(得分:0)

SELECT cd.custNo, --What you want to see
,ISNULL(c1.subcusNo,c2.parentcusNo) AS Matched_Customer_No
FROM customerdetails cd
    LEFT JOIN cusparentsub c1
        ON c1.subcusNo = cd.custNo
    LEFT JOIN cusparentsub c2
        ON c2.parentcusNo = cd.custNo