2015-04-07 46 views
1

嗨,我在這裏有一些問題。

這裏是我的示例數據庫
分組依據並在SQL中添加多列

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

注意

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


我怎樣才能創建一個表,使它看起來像這樣

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

概念理論值'PIVOT',這_RDBMS_這是什麼? –

+0

可能重複[SQL Server PIVOT示例?](http://stackoverflow.com/questions/24470/sql-server-pivot-examples) –

+0

你能教我如何使用PIVOT?我不是很親密 – user1647667

回答

0

在這裏你去,靜態支點

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 | - 

編輯

剛纔看到你需要動態PIVO評論牛逼,在這裏你去:

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 | - 
+0

非常感謝你 – user1647667

+0

歡迎你。祝你好運,快樂的編碼。 –