使用SQL 2008透视数据

时间:2010-12-29 05:17:37

标签: sql sql-server-2008

我在这方面遇到了一些问题。

SELECT a.[Id]
  ,a.[Ext]
  ,a.[Title]
  ,b.Text
  FROM [Sliders] a
  LEFT OUTER JOIN SliderItems b on b.SliderId = a.Id

返回如下数据集:

Id                                    Ext   Title       Text
1140E5F9-7ABB-42D6-B054-9D30461FC4A9 .jpg Test me big asdftyrthg
1140E5F9-7ABB-42D6-B054-9D30461FC4A9 .jpg Test me big asdfd22sdf
1140E5F9-7ABB-42D6-B054-9D30461FC4A9 .jpg Test me big asdf342324543
1140E5F9-7ABB-42D6-B054-9D30461FC4A9 .jpg Test me big asdf;l;po09

我真正需要做的是将数据转出,以便不同的文本项分别位于各自的列中。

感谢。

编辑:我认为这是更接近的,但是它告诉我列数ID被多次指定,不能摆脱那个。

SELECT *
FROM
(SELECT Id, Title FROM Sliders)AS a
LEFT JOIN SliderItems s on (s.SliderId = a.Id)
PIVOT
(
  MAX(s.Text)
FOR s.Text IN ([One],[Two],[Three],[Four])
) AS p

1 个答案:

答案 0 :(得分:1)

SELECT *
FROM
(
  SELECT a.Id, a.Title, b.Text
  FROM dbo.Sliders AS a
  LEFT JOIN dbo.SliderItems b on b.SliderId = a.Id
) AS s
PIVOT
(
  MAX(s.Text)
  FOR s.Text IN ([One],[Two],[Three],[Four])
) AS p