透视行到列

时间:2012-07-17 18:22:41

标签: sql tsql sql-server-2005 pivot unpivot

我试图转动一张桌子并且遇到一些困难。我的表架构如下所示:

ID  W_C    W_P      A_C   A_P
3   257    251342   217   206078
4   443    109023   332   87437
6   17     9985     32    13515

我想要实现的目标是:

        3       4       6
w_c     257     443     17
w_p     251342  109023  9985
a_c     217     332     87437
a_p     206078  87437   13515

我不需要显示w_cw_pa_ca_p我只是将其用作参考点。

我认为可能有一种方法可以使用pivot / unpivot,但我对它们并不是很熟悉,而且我所读到的内容并没有帮助我。

我尝试使用CTE做一些事情,但我认为它过于复杂,只是不好的做法:

;with [3_Data] as (
    Select
        1 as [common_key3]
        ,max(Case when [id] = 3 then [w_c] else 0 end) as [3_Records]
    From [example]
), [4_data] as (
Select
        1 as [common_key4]
        ,max(Case when [id] = 4 then [w_c] else 0 end) as [4_Records]
    From [example]
), [6_data] as (
    Select
        1 as [common_key6]
        ,max(Case when [id] = 6 then [w_c] else 0 end) as [6_Records]
    From [example]
)
Select [3_Records], [4_Records], [6_Records]
From [3_Data]
    inner join [4_data] on [common_key3] = [common_key4]
    inner join [6_data] on [common_key3] = [common_key6]

Sql已经创建了表格http://sqlfiddle.com/#!3/02ef2/6

1 个答案:

答案 0 :(得分:3)

您可以使用UNPIVOT,然后使用PIVOT来获得所需的结果(请参阅SQL Fiddle with Demo):

select col, [3], [4], [6]
from
(
  select id, value, col
  from
  (
    select id, w_c, w_p, a_c, a_p
    from t
  ) x
  unpivot
  (
    value
    for col in (w_c, w_p, a_c, a_p)
  )u
) x1
pivot
(
  sum(value)
  for id in ([3], [4], [6])
) p

在此查询中,您将首先UNPIVOT,这样您就可以更轻松地访问要转换的数据。您可以对valuecol字段使用任何名称,我只是为此示例选择了该名称。数据取消后,您可以应用PIVOT来获取最终产品。