1

我正在尝试旋转表格并且遇到了一些困难。我的表架构如下所示:

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_c, w_p, a_c, 或者a_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 fiddle 已经创建了表:http ://sqlfiddle.com/#!3/02ef2/6

4

1 回答 1

3

您可以使用 anUNPIVOT然后 aPIVOT来获得您想要的结果(参见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

In this query you will first, UNPIVOT which will allow you easier access to the data to transform. You can use whatever names you want for the value and col fields, I just chose that for this example. Once the data is unpivoted, you can then apply a PIVOT to get the final product.

于 2012-07-17T18:50:49.093 回答