SQL透视列

时间:2012-10-19 19:17:08

标签: sql-server tsql pivot unpivot

假设我创建了一个临时表,结构/数据看起来像这样

  Type        Lang    N_cnt        Pcnt      T1      T2       T3      T4
============================================================================
ClassroomA      1      165897      1232     6439    1135     4516     1756
ClassroomA      2      175127      1254     6439    1135     1285     1953
ClassroomB      1      179515      1284     6439    1762     3945     1957
ClassroomB      2      159683      2041     6439    1575     4745     1955

我想转动T1T2T3T4列,以便获得此结果

   Type       SubType   Lang      N_cnt            P_cnt   
==============================================================
ClassroomA      NULL     1       165897          1232  
NULL            "T1"     1   6439/165897     6439/1232       
NULL            "T2"     1       *calculation*   *calculation*
NULL            "T3"     1       *calculation*   *calculation*
NULL            "T4"     1       *calculation*   *calculation*
ClassroomA      NULL     2       175127          1254  
NULL            "T1"     2       6439/175127     6439/1254       
NULL            "T2"     2       *calculation*   *calculation*
NULL            "T3"     2       *calculation*   *calculation*
NULL            "T4"     2       *calculation*   *calculation*

请注意,calculation表示我将使用T{x}的值并对其进行一些计算(我为第一个T1做一个示例)。我还想补充一点,实际上我对这些T个变量大概有十个。

如何转动列?

1 个答案:

答案 0 :(得分:3)

你可以使用类似的东西:

select type, 
  case when subtype = 'start' then null else subtype end subtype,
  lang, 
  case when subtype = 'start' then n_cnt else value/(n_cnt * 1.0) end n_cnt,
  case when subtype = 'start' then pcnt else value/(pcnt * 1.0) end pcnt
from
(
  select type, lang, n_cnt, pcnt, 
    T1, T2, T3, T4, 0 as start
  from table1
) x
unpivot 
(
  value 
  for subtype in (T1, T2, T3, T4, start)
) un
order by type, lang, subtype;

请参阅SQL Fiddle with Demo