我有以下表格数据
Id Name Email Address
1 abc abc@xyz.com abc_address
2 pqr pqr@xyz.com pqr_address
3 mno mno@xyz.com mno_address
上表所需的输出结果:
CC1_Name CC1_Email CC1_Address CC2_Name CC2_Email CC2_Address CC3_Name CC3_Email CC3_Address
abc abc@xyz.com abc_address pqr pqr@xyz.com pqr_address mno mno@xyz.com mno_address
我知道可以在SQL select查询中使用PIVOT函数。但由于某种原因,我无法实现它。
答案 0 :(得分:1)
你可以使用这样一个简单的方法:
SELECT
MAX(CASE WHEN Id = 1 THEN Name END) AS CC1_Name,
MAX(CASE WHEN Id = 1 THEN Email END) AS CC1_Email,
MAX(CASE WHEN Id = 1 THEN Address END) AS CC1_Address,
MAX(CASE WHEN Id = 2 THEN Name END) AS CC2_Name,
MAX(CASE WHEN Id = 2 THEN Email END) AS CC2_Email,
MAX(CASE WHEN Id = 2 THEN Address END) AS CC2_Address,
MAX(CASE WHEN Id = 3 THEN Name END) AS CC3_Name,
MAX(CASE WHEN Id = 3 THEN Email END) AS CC3_Email,
MAX(CASE WHEN Id = 3 THEN Address END) AS CC3_Address
FROM yourTable;
要以动态方式使用查询,您需要使用动态SQL,如下所示:
DECLARE @sql nvarchar(max) = '';
SELECT @sql = @sql + ',' + 'MAX(CASE WHEN Id = ' + CAST(Id AS varchar(3)) + 'THEN Name END) AS CC'+ CAST(Id AS varchar(3)) + '_Name,'
+ 'MAX(CASE WHEN Id = ' + CAST(Id AS varchar(3)) + 'THEN Email END) AS CC' + CAST(Id AS varchar(3)) + '_Email,'
+ 'MAX(CASE WHEN Id = ' + CAST(Id AS varchar(3)) + 'THEN Address END) AS CC' + CAST(Id AS varchar(3)) + '_Address'
FROM yourTable;
SET @sql = 'SELECT ' + SUBSTRING(@sql, 2, LEN(@sql)) + ' FROM yourTable';
EXEC(@sql);