T-SQL 透视表和反透视表
Transact SQL 中的 Pivot(透视)和 Unpivot(反透视) 是关系运算符。它们将一个表转换为另一个表,以实现清晰的表视图。
Pivot(透视) 运算符将 行数据 转换为 列数据。
Unpivot(反透视) 关系运算符与 Pivot 运算符相反。它将基于列的数据转换为基于行的数据,并将基于行的数据转换为基于列的数据。
语法
1. Pivot:
SELECT (ColumnNames) /Write column names
FROM (TableName) /table name
PIVOT
(
AggregateFunction(Column To Be Aggregate)
FOR PivotColumn IN (Pivot Column Value)
) AS (Alias) //Alias is a name of the table
2. UnPivot:
SELECT (ColumnNames) /Name of column
FROM (TableName)
UNPIVOT
(
Aggregate Function (Column which is Aggregated)
FOR Pivot Column IN (PivotColumnValues)
) AS (Alias)
示例1-
在这里,我们创建一个表名为 “javatpoint“,值为 Course name, Course category, Price, and Values。
Create Table javatpoint
(
CourseName nvarchar(50),
CourseCategory nvarchar(50),
Price int
)
Insert into Javatpoint values('C', 'PROGRAMMING', 5000)
Insert into Javatpoint values('JAVA', 'PROGRAMMING', 6000)
Insert into Javatpoint values('PYTHON', 'PROGRAMMING', 8000)
Insert into Javatpoint values('PLACEMENT 100', 'INTERVIEWPREPARATION', 5000)
SELECT * FROM Javatpoint
我们得到的输出是:
COURSE NAME | COURSE CATEGORY | PRICE |
---|---|---|
C | PROGRAMMING | 5000 |
JAVA | PROGRAMMING | 6000 |
PYTHON | PROGRAMMING | 8000 |
PLACEMENT 100 | INTERVIEW PREPARATION | 5000 |
现在,将 Pivot 运算符应用于此数据:
SELECT Course Name, PROGRAMMING, INTERVIEW PREPARATION
FROM Javatpoint
PIVOT
(
SUM(Price) FOR CourseCategory IN (PROGRAMMING, INTERVIEW PREPARATION )
) AS PivotTable
使用 Pivot 运算符后,我们得到以下结果:
COURSE NAME | PROGRAMMING | INTERVIEW PREPARATION |
---|---|---|
C | 5000 | NULL |
JAVA | 6000 | NULL |
PLACEMENT 100 | NULL | 5000 |
PYTHON | 8000 | NULL |
示例2-
现在,我们使用上面例子中创建的相同表 ” Javatpoint” ,并将 Unpivot 操作符应用于我们的 Pivoted 表。
应用 UNPIVOT 操作符如下:
SELECT CourseName, CourseCategory, Price
FROM
(
SELECT CourseName, PROGRAMMING, INTERVIEW PREPARATION FROM Javatpoint
PIVOT
(
SUM(Price) FOR CourseCategory IN (PROGRAMMING, INTERVIEW PREPARATION)
) AS PivotTable
) P
UNPIVOT
(
Price FOR CourseCategory IN (PROGRAMMING, INTERVIEW PREPARATION)
)
AS UnpivotTable
使用 Unpivot 运算符后,我们成功将表的列转换回行,得到了原始表:
COURSE NAME | COURSE CATEGORY | PRICE |
---|---|---|
C | PROGRAMMING | 5000 |
JAVA | PROGRAMMING | 6000 |
PLACEMENT100 | INTERVIEW PREPARATION | 5000 |
PYTHON | PROGRAMMING | 8000 |