在這裏你去,靜態支點:
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 | -
概念理論值'PIVOT',這_RDBMS_這是什麼? –
可能重複[SQL Server PIVOT示例?](http://stackoverflow.com/questions/24470/sql-server-pivot-examples) –
你能教我如何使用PIVOT?我不是很親密 – user1647667