如何在没有聚合的情况下部分转置SQL表

时间:2016-12-13 10:08:40

标签: sql sql-server

我需要你们'有关部分转置此MS SQL表的专家建议:

| Term | Listening | Reading | Speaking | Writing |
| AC1  | 12        | 15      | 18       | 13      |
| AC2  | 17        | 14      | 9        | 12      |

进入这个:

| Term | Comp      | Score |
| AC1  | Listening | 12    |
| AC1  | Reading   | 15    |
| AC1  | Speaking  | 18    |
| AC1  | Writing   | 13    |
| AC2  | Listening | 17    |
| AC2  | Reading   | 14    |
| AC2  | Speaking  | 9     |
| AC2  | Writing   | 12    |

感谢您是否可以提供建议。提前谢谢。

3 个答案:

答案 0 :(得分:4)

你想要的是UNPIVOT

SELECT Term, Comp, Score
FROM mytable
UNPIVOT
   (Score FOR Comp IN 
      ([Listening], [Reading], [Speaking], [Writing])
)AS unpvt;

答案 1 :(得分:4)

EnvUtils.copy(inheritableThreadInfo)

输出

SELECT term,comp,trems
FROM 
   (SELECT *
   FROM #b) p
UNPIVOT
   (trems FOR comp IN 
      (Listening, Reading, Speaking, Writing)
)AS unpvt;
GO

term    comp    trems
AC1 Listening   12
AC1 Reading     15
AC1 Speaking    18
AC1 Writing     13
AC2 Listening   17
AC2 Reading     14
AC2 Speaking    9
AC2 Writing     12

答案 2 :(得分:4)

您只需使用 UNPIVOT 即可将列转换为行。

 SELECT
    term,comp,trems
    FROM #b
    CROSS APPLY (
          Values
             ('Listening' , Listening),
             ('Reading' , Reading),
             ('Speaking', Speaking) ,
             ('Writing', Writing)
      ) as CA (comp, trems)

   output


term    comp    trems
AC1 Listening   12
AC1 Reading     15
AC1 Speaking    18
AC1 Writing     13
AC2 Listening   17
AC2 Reading     14
AC2 Speaking    9
AC2 Writing     12