-3

I am trying to pull 3 columns of data from one field. basically i have a field with for arguments sake a table with the following data:

  • Color,
  • Model,
  • Year of a car.

It is itemized as ID4 is Color, ID5 is Model and ID6 is Year. I can pull one data set with no problem using a filter, ex. Filter = 4, 5 or 6. But I cannot pull multiples as I just get the headers and no data at all.

4

1 回答 1

0

假设您使用的是 SQL Server 2005+,并且您的问题实际上是“如何根据同一个表中的另一个字段将表中的一列分解为多个命名列”,这是一个以您的问题为模式的简单示例。

给出这个数据集:

declare @tbl table (id int, tag char(3), data varchar(255))

insert into @tbl values
(1, 'ID4', 'Red'), (1, 'ID5', 'Toyota'), (1, 'ID6', '1999'),
(2, 'ID4', 'Blue'), (2, 'ID5', 'Honda'), (2, 'ID6', '2000'),
(3, 'ID4', 'Green'), (3, 'ID5', 'Nissan'), (3, 'ID6', '2004'),
(4, 'ID4', 'Red'), (4, 'ID5', 'Nissan'), (4, 'ID6', '1990'),
(5, 'ID4', 'Black'), (5, 'ID5', 'Toyota'), (5, 'ID6', '2002')

一个简单的select语句返回此数据:

select * from @tbl

id  tag  data
1   ID4  Red
1   ID5  Toyota
1   ID6  1999
2   ID4  Blue
2   ID5  Honda
2   ID6  2000
3   ID4  Green
3   ID5  Nissan
3   ID6  2004
4   ID4  Red
4   ID5  Nissan
4   ID6  1990
5   ID4  Black
5   ID5  Toyota
5   ID6  2002

pivot查询返回数据——每辆车一行——颜色、型号和年份作为它们自己的列:

select id, [ID4] as 'Color', [ID5] as 'Model', [ID6] as 'Year'
from (select id, tag, data from @tbl) as p
pivot (max(data) for tag in ([ID4], [ID5], [ID6])) as pvt
order by pvt.id

这是输出的样子:

id  Color  Model   Year
1   Red    Toyota  1999
2   Blue   Honda   2000
3   Green  Nissan  2004
4   Red    Nissan  1990
5   Black  Toyota  2002
于 2012-09-18T00:53:57.007 回答