如何将行转移到新列下的列和列数据?

时间:2014-11-02 17:05:32

标签: sql-server

我有这张桌子 http://sqlfiddle.com/#!3/641f9

enter image description here

我希望选择它看起来像这样

enter image description here

在Sql Server 2008中如何实现? 对我来说非常重要,谢谢。

1 个答案:

答案 0 :(得分:1)

我认为这就是你想要的:

IF OBJECT_ID(N'tempdb..#Temp') IS NOT NULL 
  BEGIN
    DROP TABLE #Temp
  END
SELECT
  sd.Company,
  sd.Brand,
  'DateFrom' AS Variable,
  sd.DateFrom AS [Date],
  sd.WeekName
INTO
  #temp
FROM
  dbo.SourceData AS sd
UNION ALL
SELECT
  sd.Company,
  sd.Brand,
  'DateTo' AS Variable,
  sd.DateTo AS [Date],
  sd.WeekName
FROM
  dbo.SourceData AS sd

SELECT
  Company,
  Variable,
  Brand,
  NOVW42012,
  MAYW42014,
  AUGW32014,
  APRW12013,
  AUGW52013,
  MARW22014
FROM
  (
   SELECT
    Company,
    Variable,
    Brand,
    [Date],
    WeekName
   FROM
    #temp
  ) sd PIVOT
( MIN(sd.[Date]) FOR WeekName IN (NOVW42012, MAYW42014, AUGW32014, APRW12013,
                                  AUGW52013, MARW22014) ) AS PVT
ORDER BY
  Company,
  Brand