1

Hi I have here some question.

Here is my sample database

001 | A | AC 
001 | B | AC 
002 | A | IN 
002 | C | AC 
003 | A | AC 

Notes

Column 1 - Should be the column header 
Column 2 - Should be the row header 
Column 3 - Should be the data 


how can I create a table to make it look like this

- | 001 | 002 | 003 
A | AC  | IN  | AC 
B | AC  |  -  | -  
C | -   | AC  | -  
user1647667
  • 1,269
  • 4
  • 14
  • 26

1 Answers1

0

Here you go, static pivot:

CREATE TABLE dbo.tbl (
    col1 VARCHAR(20) NOT NULL,
    col2 VARCHAR(20) NOT NULL,
    col3 VARCHAR(20) NOT NULL
);

INSERT INTO dbo.tbl (col1, col2, col3)
VALUES ('001', 'A', 'AC'),
       ('001', 'B', 'AC'),
       ('002', 'A', 'IN'),
       ('002', 'C', 'AC'),
       ('003', 'A', 'AC');


SELECT col2 as [ ], [001], [002], [003]
FROM 
    (
        SELECT col1, col2, col3 
        FROM tbl
    ) AS t1 
PIVOT 
(
    MAX(col3) 
    FOR col1 IN ([001], [002], [003]) 
) AS t2

OUTPUT:

  | 001 | 002 | 003 
A | AC  | IN  | AC 
B | AC  |  -  | -  
C | -   | AC  | - 

EDIT

Just now saw comments that you need dynamic pivot, here you go:

DECLARE @cols   AS NVARCHAR(MAX) = '',
        @sql    AS NVARCHAR(MAX)

SELECT @cols += QUOTENAME((col1)) + ','
                    FROM   (
                            SELECT  DISTINCT col1
                            FROM    tbl                         
                            ) a 

SET @cols   = LEFT(@cols, LEN(@cols) - 1)
SET @sql    = 'SELECT * 
               FROM 
                    (
                        SELECT col1, col2 as [ ], col3 
                        FROM tbl
                    ) x 
                    PIVOT
                    (
                        MAX (col3)
                        FOR col1 IN (' + @cols + ') 
                    ) p'

EXEC sp_executesql @sql

OUTPUT:

  | 001 | 002 | 003 
A | AC  | IN  | AC 
B | AC  |  -  | -  
C | -   | AC  | -