如何在与另一个表连接时在一行中显示查询结果

时间:2014-07-16 22:40:14

标签: sql sql-server-2012 pivot

我尝试过搜索但我无法找到解决方案。我正在尝试连接两个表,基本上表2有来自表1的一行的多行。但是在显示时,我想列出表1中的所有列以及表2中的所有字段,但是在一行中。即表2行将显示为列。

Table 1

ID  Col2    Col3    Col4
1   John    Smith   CA
2   Henry   Bond    FL

表2

ID (FK) Type    Value
1   Car1        Honda
1   Car2        Toyota
2   Car1        Honda
2   Car2        Nissan
3   Car3        Audi

结果应为

ID  Col2    Col3    Col4    Car1    Car2    Car3
1   John    Smith   CA      Honda   Toyota  
2   Henry   Bond    FL      Honda   Nissan  Audi

1 个答案:

答案 0 :(得分:0)

你是否经历过这样的事情?

SQL小提琴:http://sqlfiddle.com/#!6/a379d/2

create table people
(
  id bigint not null identity(1,1) primary key
  , firstName nvarchar(32)
  , lastName nvarchar(32)
  , state nchar(2)
)
create table personCar
(
  id bigint not null identity(1,1) primary key
  , personId bigint not null
  , carType nvarchar(32)
  , carModel nvarchar(32)
)

insert people select 'John', 'Smith', 'CA'
insert people select 'Henry', 'Bond', 'FL'

insert personCar select 1, 'Car1', 'Honda'
insert personCar select 1, 'Car2', 'Toyota'
insert personCar select 2, 'Car1', 'Honda'
insert personCar select 2, 'Car2', 'Nissan'
insert personCar select 2, 'Car3', 'Audi'


select firstName, lastName, state
, [Car1], [Car2], [Car3]
from 
(
  select firstName, lastName, state, carModel, carType
  from people p
  inner join personCar c
  on c.personId = p.id
) x
pivot 
(
  max(carModel) for carType in ([Car1], [Car2], [Car3])
) pvt