From MS SQL Server 2005 Microsoft has introduced pivot and UNPIVOT to achieve the row and column conversion, which greatly facilitates us to store data and render data. Today, the two keywords are analyzed, combined with examples to explain how to store data, how to render data.
For example, there is a table in the student selection and performance system, which stores the student's course scores, and we can't predict how much the course will be, so the general table is designed as follows:
Figure 1
The last column is the course number, so it doesn't matter whether or not the course will be added to students ' choice after school. So the report that we want to present to the user is generally like this:
Figure 2
You can see the storage of data when the use of the column-type storage, the final rendering of data is row-style display, how to achieve? The following detailed analysis explains:
Create a Table statement
Copy Code code as follows:
Use [master]
Go
/****** object:table [dbo]. [Table_1] Script date:08/06/2013 13:55:39 ******/
SET ANSI_NULLS on
Go
SET QUOTED_IDENTIFIER ON
Go
SET ansi_padding on
Go
CREATE TABLE [dbo]. [Table_1] (
[Name] [varchar] () not NULL,
[Score] [Real] Not NULL,
[SUBJECT_ID] [INT] Not NULL
) on [PRIMARY]
Go
SET ansi_padding off
Go
Inserting test data
Copy Code code as follows:
insert into [master]. [dbo]. [Table_1] ([name],[score],[subject_id]) VALUES (' John ', 90, 1);
insert into [master]. [dbo]. [Table_1] ([name],[score],[subject_id]) VALUES (' John ', 80, 2);
insert into [master]. [dbo]. [Table_1] ([name],[score],[subject_id]) VALUES (' John ', 70, 3);
insert into [master]. [dbo]. [Table_1] ([name],[score],[subject_id]) VALUES (' Harry ', 50, 1);
insert into [master]. [dbo]. [Table_1] ([name],[score],[subject_id]) VALUES (' Harry ', 40, 2);
insert into [master]. [dbo]. [Table_1] ([name],[score],[subject_id]) VALUES (' Dick ', 60, 1);
Now that the data in Table_1 is the result in Figure 1, now we want to get the result of Figure 2, then use the following statement:
Copy Code code as follows:
SELECT [Name],[1],[2],[3]
from [master]. [dbo]. [Table_1]
Pivot
(
SUM (score) for subject_id in ([1],[2],[3])
) AS Pvt
Go
If the database table is stored as shown in Figure 2, to be rendered in Figure 1, then you need to use Unpivot to do this:
Copy Code code as follows:
SELECT [Name],[subject_id],[score]
From
(
SELECT [Name],[1],[2],[3]
from [master]. [dbo]. [Table_1]
Pivot
(
SUM (score) for subject_id in ([1],[2],[3])
) AS Pvt
) p
Unpivot
(
Score for subject_id in ([1],[2],[3])
) as Unpvt
Of course, I still on the basis of Table_1 with PVT into the way of line storage, and then use UNPIVOT for the column-style rendering.