I have a table as shown below:
Example :
CREATE TABLE matrix
(
a VARCHAR(10),
b VARCHAR(10)
);
INSERT INTO matrix VALUES('A','H')
INSERT INTO matrix VALUES('B','I')
INSERT INTO matrix VALUES('C','J')
INSERT INTO matrix VALUES('D','K')
INSERT INTO matrix VALUES('E','L')
INSERT INTO matrix VALUES('F','M')
INSERT INTO matrix VALUES('G','N')
INSERT INTO matrix VALUES('A','M')
SELECT * FROM matrix;
Looks like:
a b
-------
A H
B I
C J
D K
E L
F M
G N
A M
Now I want to show the result in the following matrix format:
Expected Result:
H I J K L M N
--------------------------------------
A | 1 0 0 0 0 1 0
|
B | 0 1 0 0 0 0 0
|
C | 0 0 1 0 0 0 0
|
D | 0 0 0 1 0 0 0
|
E | 0 0 0 0 1 0 0
|
F | 0 0 0 0 0 1 0
|
G | 0 0 0 0 0 0 1
DECLARE @DynamicPivotQuery AS NVARCHAR(max)
DECLARE @ColumnName AS NVARCHAR(max)
DECLARE @ColumnName1 AS NVARCHAR(max)
SELECT @ColumnName = Isnull(@ColumnName+',', '') + b,
@ColumnName1 = Isnull(@ColumnName1+',', '') + 'isnull(' + b + ',0)' + ' as ' + b
FROM ( SELECT DISTINCT b FROM matrix) AS qry1
--Select @ColumnName,@ColumnName1
SET @DynamicPivotQuery =
' Select ' + @ColumnName1 + '
from (Select *,1 ''VALUE'' from matrix ) as t pivot ( Sum(VALUE ) for b in (' + @ColumnName + '))
as pvt '
--print @DynamicPivotQuery
EXEC Sp_executesql @DynamicPivotQuery
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.