在t-sql中将两个返回的行合并为一个

时间:2014-04-25 11:41:25

标签: sql-server sql-server-2008 tsql sql-server-2008-r2

我有以下查询返回包含人员详细信息的结果。我在数据库中有2个人类型作为OWNER和CONTACT。我只需要OWNER的姓名和地址以及CONTACT的电子邮件。

我写了以下查询,请检查。

SELECT DISTINCT 
        s.[id],
        s.[entity_id],
            s.[transfered],
        s.[meta],
        s.[operation]
        c.[Company_Name] as CompanyName,
        ISNULL(pa.HouseName,'') as HouseName,
        ISNULL(pa.Street,'') as Street,
        ISNULL(pa.Town,'') as Town,
        ISNULL(pa.City,'') as City,
        ISNULL(pa.County,'') as County,
        ISNULL(pa.Country,'') as Country,
        ISNULL(pa.Postcode,'') as PostCode,     
        ISNULL(p.Title,'') as Title,
        ISNULL(p.Forenames,'') as FirstName,
        ISNULL(p.Surname,'') as LastName,
        ISNULL(pc.Email,'') as Email

  FROM 
        dbo.COMPANY c INNER JOIN dbo.Sage_Company_Sync s ON s.entity_id = c.Company_ID
        INNER JOIN dbo.CompanyPostalAddress cpa ON c.Company_ID = cpa.CompanyId
        INNER JOIN dbo.POSTAL_ADDRESS pa ON cpa.PostalAddressId = pa.Address_ID
        LEFT JOIN dbo.CompanyPerson cp ON cp.CompanyId = c.company_id
        INNER JOIN dbo.PERSON p ON p.Person_ID = cp.PersonId
        INNER JOIN dbo.PERSON pc ON pc.Person_ID = cp.PersonId

  WHERE 
        cpa.PostalAddressTypeId = 2
        and cp.PersonTypeId in (1,2)
        and s.transfered = 0
        and s.entity_type = 'company'       
  ORDER BY 
        s.operation ASC

以上查询返回2行。一个用于OWNER,一个用于COMPANY。我的问题是如何才能使我的查询只返回OWNER的姓名和地址详细信息以及联系人的电子邮件一行?

更新

结果

 id entity_id   transfered  meta    operation   CompanyName HouseName   Street  Town    City    County  Country PostCode    Title   FirstName   LastName    Email   PersonType
5   25  0       U   Testing     2  (home Address)   Stoneleigh  Epsom   Surrey  Uk  KTJ19 0PQ   Mr  Dfdf    Dfdf    test@gmail.com  CONTACT
5   25  0       U   Testing     2  (home Address)   Stoneleigh  Epsom   Surrey  Uk  KT1J9 0PQ   Mr  Testing     Testing     OWNER

期望的结果

id  entity_id   transfered  meta    operation   CompanyName HouseName   Street  Town    City    County  Country PostCode    Title   FirstName   LastName    Email   PersonType
5   25  0       U   Testing     2 Westways (home Address)   Stoneleigh  Ezpsofm Surrey  Uk  KT19 Q  Mr  Testing     Testing test@gmail.com  OWNER

电子邮件实际上是联系人电子邮件。

谢谢,

1 个答案:

答案 0 :(得分:1)

您可以将查询结果存储在临时表或公用表表达式中,并在其上构建另一个查询。

考虑以下示例:

DECLARE @tbl TABLE (ID INT, Name VARCHAR(20), Email VARCHAR(20), Relation VARCHAR(20))

INSERT INTO @tbl VALUES (1, 'Somebody', 'xyz@domain.com', 'Employer'), (1, 'Someone', 'Test', 'Employee');

WITH cte1 AS
(
    SELECT * FROM @tbl WHERE Relation = 'Employer'
),
cte2 AS
(
    SELECT t.ID, t.Name, c.Email, t.Relation FROM cte1 c INNER JOIN @tbl t ON c.ID = t.ID WHERE t.relation = 'Employee'
)

SELECT* FROM cte2

您还可以查看此SQLFiddle示例:

SQLFiddle