我有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)
我想以这种形式收到报告:
答案 0 :(得分: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;