Pivoting Data
Pivoting is a technique that groups and aggregates data, transitioning it from a state of rows to a state of columns. In all pivot queries, you need to identify three elements:
- What do you want to see on rows? This element is known as the on rows, or grouping element
- What do you want to see on columns? This element is known as the on cols, or spreading element.
- What do you want to see in the intersection of each distinct row and column value? This element is known as the data, or aggregation element.
pattern:
WITH PivotData AS
(
SELECT
< grouping column >,
< spreading column >,
< aggregation column >
FROM < source table >
)
SELECT < select list >
FROM PivotData
PIVOT( < aggregate function >(< aggregation column >)
FOR < spreading column > IN (< distinct spreading values >) ) AS P;
I have this table created in SQL Server
CREATE TABLE [dbo].[NameValueData](
[Name] [VARCHAR](50) NOT NULL,
[Value] [INT] NOT NULL
) ON [PRIMARY]
and It has values
INSERT INTO NameValueData
VALUES
( 'N1', 1 ),
( 'N2', 2 ),
( 'N3', 3 ),
( 'N4', 4 ),
--NOT FIXED Number of ROWS
And data is:
Name Value
N1 1
N2 2
N3 3
N4 4
... ...
Now I need to rotate this Data and get results where columns names created based on row values from Column Name
N1 N2 N3 N4 ...
1 2 3 4 --Can be more
I tried to write my own Pivot SQL
WITH PivotData
AS (SELECT Value AS GroupingColumn,
Name AS SpreadingColumn,
Value AS AggregationColumn
FROM dbo.NameValueData)
SELECT 1 AS Ignore,
[N1],
[N2],
[N3],
[N4]
FROM PivotData
PIVOT
(
MAX(AggregationColumn)
FOR SpreadingColumn IN ([N1], [N2], [N3], [N4])
) AS P;
Result is:
Ignore N1 N2 N3 N4
1 1 NULL NULL NULL
1 NULL 2 NULL NULL
1 NULL NULL 3 NULL
1 NULL NULL NULL 4
Why I get 4 rows here?