需要通过SQL转置列

时间:2015-05-13 16:06:24

标签: sql sql-server pivot

我整天都在谷歌搜索试图找出如何通过SQL转置我的数据,但我只是没有得到它。我有一个数据表,我需要转置列。

我的原始表格如下:

enter image description here (列名在顶行)

我想转置列,以便我的结果如下:

enter image description here

有人可以帮助我使用正确的代码来获得我需要的结果吗?我无法通过Excel进行转置​​,因为数据是动态的。

编辑: 我试过这段代码:

SELECT [Gift Level], Goal
FROM
(   SELECT * FROM GiftPyramidDollars)
AS Result
Unpivot
(Goal for [Gift Level] in ([< $25,000], [$25,000], [$50,000], [$100,000], [$200,000], [$250,000], [$500,000], [$1,000,000], [$2,500,000], [$5,000,000], [$10,000,000])
)
AS UnPvt

但它没有将结果分成两列。这就是我得到的:

Gift Level      Goal
< $25,000   0.00
$25,000         0.00
$50,000         0.00
$100,000    8000000.00
$200,000    10000000.00
$250,000    6250000.00
$500,000    12500000.00
$1,000,000  30000000.00
$2,500,000  12500000.00
$5,000,000  10000000.00
$10,000,000 10000000.00
< $25,000   58126.67
$25,000         260687.75
$50,000         394300.00
$100,000    352233.61
$200,000    800000.00
$250,000    2110000.00
$500,000    4603423.93
$1,000,000  11500000.00
$2,500,000  0.00
$5,000,000  5000000.00
$10,000,000 0.00

1 个答案:

答案 0 :(得分:0)

SELECT B.[Gift Level]
     , [$ Goal] = MAX(CASE B.Campaign WHEN '$ Goal' THEN B.Goal END)
     , [$ Raised to Date] = MAX(CASE B.Campaign WHEN '$ Raised to Date' THEN B.Goal END)
FROM GiftPyramidDollars A
UNPIVOT(A.Goal FOR [Gift Level] IN (
    [< $25,000]
  , [$25,000]
  , [$50,000]
  , [$100,000]
  , [$200,000]
  , [$250,000]
  , [$500,000]
  , [$1,000,000]
  , [$2,500,000]
  , [$5,000,000]
  , [$10,000,000])
) B
GROUP BY B.[Gift Level]