2014-09-29 67 views
1

我有3个数据表,我想创建一个报告,显示我的人与他们的书籍和家具。最大的问题是要获得一个有两列的独立清单:书籍和家具。报告与两个独立的列

create table people (id int primary key) 
create table books (id int primary key 
    , personId int foreign key references people(id)) 
create table furnitures (id int primary key 
    , personId int foreign key references people(id)) 
go 

insert into people(id) 
values (1),(2),(3) 
insert into books(id,personId) 
values (1,1),(2,1),(3,1),(4,1),(5,1),(6,3),(7,3) 
insert into furnitures(id,personId) 
values (1,2),(2,2),(3,2),(4,3),(5,3),(6,3),(7,3),(8,3) 

我想以这种形式获得的报告:

enter image description here

回答

2

你需要做一个join,但你没有钥匙。所以,我们使用row_number()创建一个。剩下的只是一个full outer join来组合数据:

select coalesce(b.personId, f.personId) as personId, b.id as bookid, f.id as furnitureid 
from (select b.*, row_number() over (partition by personId order by id) as seqnum 
     from books b 
    ) b 
    full join 
    (select f.*, row_number() over (partition by personId order by id) as seqnum 
     from furnitures f 
    ) f 
    on f.personId = b.personId and b.seqnum = f.seqnum;