如何在sql Sever中创建数据透视表

时间:2018-03-19 10:11:34

标签: sql sql-server sql-server-2008

我有一个表(Table_Marks),它包含如下所述的值: -

CLASS | STD | NAME   | SUBJECT | PT1_M | PTB1_M | PT2_M | PTB2_M | 
1     | ST1 | NITYA  | ENG     | 12    | 15     | 30    | 9      |
1     | ST1 | NITYA  | HIN     | 2     | 22     | 25    | 6      |
1     | ST1 | NITYA  | MATH    | 3     | 10     | 32    | 8      |
1     | ST2 | SHIV   | ENG     | AB    | AB     | 10    | 2      |
1     | ST2 | SHIV   | HIN     | 2     | 22     | 20    | 1      |
1     | ST2 | SHIV   | MATH    | 3     | 10     | AB    | 5      |

现在我想将它用作PIVOT TABLE,如下所述: -

CLASS|STD |NAME  |ENG     |HIN    |MATH   |T1 |ENG    |HIN    |MATH   |T2  |T1+T2|
                 |PT1|PB1 |PT1|PB1|PT1|PB1|   |PT2|PB2|PT2|PB2|PT2|PB2|     
1    |STD1|NITYA |12 |15  |2  |22 |3  |10 |64 |30 |9  |25 |6  |32 |8  |110 |174
1    |STD2|SHIV  |AB |AB  |2  |22 |3  |10 |37 |10 |2  |20 |1  |AB |5  |38  |75

请帮助任何人

2 个答案:

答案 0 :(得分:0)

|ENG     |HIN    |MATH   |T1 |ENG    |HIN    |MATH   |T2  |T1+T2|
                 |PT1|PB1 |PT1|PB1|PT1|PB1|   |PT2|PB2|PT2|PB2|PT2|PB2| 

上面提到的列在Cassandra中被称为超级列/超级列族。如果我没有错,SQL Server 2008或大多数关系数据库中都不存在超级列。

答案 1 :(得分:0)

根据需要更改别名:

create TABLE student_marks 
(
  CLASS int,
  standard varchar(100),
  name char(20),
  SUBJECT char(20),
  PT1_M int,
  PTB1_M int,
  PT2_M int,
  PTB2_M int 
  );
  insert into student_marks values (1,'ST1','NITYA','ENG', 12,15,30,9);
  insert into student_marks values (1,'ST1','NITYA','HIN', 16,18,31,8) ;

解决方案:

SELECT
CLASS,
STANDARD,
NAME,
SUBJECT,
PT1,
PB1,
(PT1+PB1) AS  T1,
PT2,
PB2,
(PT2+PB2) AS  T2,
(PT1+PB1+PT2+PB2) AS T1T2
FROM(

SELECT
CLASS,
STANDARD,
NAME,
SUBJECT,
CASE WHEN SUBJECT in ('ENG','HIN') THEN PT1_M ELSE 0 END AS PT1,
CASE WHEN SUBJECT in ('ENG','HIN') THEN PTB1_M  ELSE 0 END AS PB1,
CASE WHEN SUBJECT in ('ENG','HIN') THEN PT2_M ELSE 0 END AS PT2,
CASE WHEN SUBJECT in ('ENG','HIN') THEN  PTB2_M  ELSE 0 END AS PB2
FROM STUDENT_MARKS
)
C