SAMPLE SELECT SQL- USING PIVOT AND UNPIVOT TABLE
PIVOT AND UNPIVOT TABLE
 
You can use the PIVOT and UNPIVOT relational operators to change a table-valued expression into another table. PIVOT rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output. And PIVOT runs aggregations where they're required on any remaining column values that are wanted in the final output. UNPIVOT carries out the opposite operation to PIVOT by rotating columns of a table-valued expression into column values.

The syntax for PIVOT provides is simpler and more readable than the syntax that may otherwise be specified in a complex series of SELECT...CASE statements. For a complete description of the syntax for PIVOT, see FROM (Transact-SQL).
SAMPLE PIVOT TABLE: 

create table #TabPivot
(
    Id int,
    Nome varchar(50),
    Categoria varchar(50)
)

insert into #TabPivot
select 1, 'João', 'A' union all
select 2, 'João', 'B'  union all
select 3, 'João', 'D'  union all
select 4, 'Maria', 'A'  union all
select 5, 'Maria', 'C' union all
select 6, 'Maria', 'D'


-- USING PIVOT
select nome,
  coalesce(A, '') CatA,
  coalesce(B, '') CatB,
  coalesce(C, '') CatC,
  coalesce(C, '') CatD
from
(
  select nome, Categoria, 'X' flag
  from #TabPivot
) d
pivot
(
  max(flag)
  for Categoria in (A, B, C, D)
) piv
Sample 01 - PIVOT TABLE 
NameCatACatBCatCCatD
JoãoXX
MariaXXX
Sample 02 - UNPIVOT TABLE:

CREATE TABLE #pvt
(
    VendorID INT
    ,Emp1 INT
    ,Emp2 INT
    ,Emp3 INT
    ,Emp4 INT
    ,Emp5 INT
)

INSERT INTO #pvt VALUES (1,4,3,5,4,4); 
INSERT INTO #pvt VALUES (2,4,1,5,5,5); 
INSERT INTO #pvt VALUES (3,4,3,5,4,4); 
INSERT INTO #pvt VALUES (4,4,2,5,5,4); 
INSERT INTO #pvt VALUES (5,5,1,5,5,5); 

 
/* Unpivot the table. */
SELECT VendorID, Employee, Orders 
FROM  
(
    SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5 FROM #pvt
) p 
UNPIVOT
(
    Orders FOR Employee IN (Emp1, Emp2, Emp3, Emp4, Emp5) 
) AS unpvt;

 
VendorIDEmployeeOrders
1Emp14
1Emp23
1Emp35
1Emp44
1Emp54
2Emp14
2Emp21
2Emp35
2Emp45
2Emp55
3Emp14
3Emp23
3Emp35
3Emp44
3Emp54
4Emp14
4Emp22
4Emp35
4Emp45
4Emp54
5Emp15
5Emp21
5Emp35
5Emp45
5Emp55
Click here to see your activities