2014-09-29 75 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;