SQL视图与两个表中的数据

时间:2010-06-13 03:12:24

标签: sql sql-server sql-server-2008 views

我似乎无法解决这个问题 - 我有两个表(PersonsCompanies),我正在尝试创建一个视图:

  1. 显示所有人

  2. 无论有多少人与之相关,
  3. 也会自行归还公司

  4. 在两个表中按名称排序

  5. 澄清一些样本数据:

    (Table: Companies)
    Id  Name
     1  Banana
     2  ABC Inc.
     3  Microsoft
     4  Bigwig
    
    (Table: Persons)
    Id  Name      RelatedCompanyId
     1  Joe Smith 3
     2  Justin    
     3  Paul Rudd 4
     4  Anjolie
     5  Dustin    4
    

    我正在寻找的输出是这样的:

     Name      PersonName CompanyName RelatedCompanyId
     ABC Inc.  NULL       ABC Inc.    NULL
     Anjolie   Anjolie    NULL        NULL
     Banana    NULL       Banana      NULL
     Bigwig    NULL       Bigwig      NULL
     Dustin    Dustin     Bigwig      4
     Joe Smith Joe Smith  Microsoft   3
     Justin    Justin     NULL        NULL
     Microsoft NULL       Microsoft   NULL
     Paul Rudd Paul Rudd  Bigwig      4
    

    正如您所看到的,新的“名称”列在两个表中排序(公司名称在人名之间正确显示),每个公司只出现一次,无论有多少人与之相关。 / p>

    这甚至可以在SQL中完成吗?!附:我正在尝试创建一个视图,以便稍后使用它来进行简单的数据检索,全文索引,并通过查询视图使编程方面更简单。

1 个答案:

答案 0 :(得分:1)

这是一种方式:

select * from (
    select Name, null as PersonName, Name as CompanyName, null as RelatedCompanyID
    from Companies
    union
    select Persons.Name as Name, Persons.Name as PersonName, Companies.Name as CompanyName, RelatedCompanyID
    from Persons
    left join Companies on Persons.RelatedCompanyID = Companies.ID
) as AggregatedData
order by AggregatedData.Name

或者使用公用表表达式稍微更可读,尽管在这种情况下没有其他真正的好处:

with AggregatedData as (
    select Name, null as PersonName, Name as CompanyName, null as RelatedCompanyID
    from Companies
    union 
    select Persons.Name as Name, Persons.Name as PersonName, Companies.Name as CompanyName, RelatedCompanyID
    from Persons
    left join Companies on Persons.RelatedCompanyID = Companies.ID
)
select * from AggregatedData
order by AggregatedData.Name