我试图在SQL multiple rows as columns (optimizing)中翻译我的问题中的查询。它在MySQL中,但我需要它也可以在MS SQL Server上运行。
一个问题是MS SQL中没有GROUP_CONCAT
,但似乎有办法模拟这个(Simulating group_concat MySQL function in Microsoft SQL Server 2005?)。
此外,我无法找到一种方法将第一个SELECT
语句存储到@sql
变量中的方式与我遇到麻烦的方式相同,因为我不知道如何正如我现在所做的那样参考colkey
。
MySQL声明:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT('MAX(CASE
WHEN ckm.colkey = ', colkey, ' THEN
(ccdr.value)
END) AS ', CONCAT('`ExtraColumn_', colkey, '`'))
) INTO @sql
FROM test_customkeymapping;
SET @sql = CONCAT('SELECT c.Name, ', @sql, '
FROM customers c
LEFT JOIN customercustomdatarels ccdr
ON c.Id = ccdr.customer
LEFT JOIN customdatas cd
ON cd.Id = ccdr.customdata
LEFT JOIN test_customkeymapping ckm
ON cd.key = ckm.customkey
GROUP BY c.Id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
答案 0 :(得分:2)
在SQL Server中,您需要进行以下更改
+
连接字符串而不是CONCAT
(除非您使用的是SQL Server 2012或更高版本)[]
)代替对象名称/别名而不是反引号(``) - QUOTENAME
将为您执行此操作c.Name
,因为它包含在选择SP_EXECUTESQL
实际执行查询所以你的查询就像:
DECLARE @SQL NVARCHAR(MAX);
SET @SQL = 'SELECT c.Name' + ( SELECT DISTINCT
', MAX(CASE WHEN ckm.colkey = '
+ QUOTENAME(colKey AS VARCHAR(10))
+ ' THEN (ccdr.value) END) AS '
+ QUOTENAME('ExtraColumn_' + CAST(colKey AS VARCHAR(10))
FROM test_customkeymapping
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)') +
'FROM customers c
LEFT JOIN customercustomdatarels ccdr
ON c.Id = ccdr.customer
LEFT JOIN customdatas cd
ON cd.Id = ccdr.customdata
LEFT JOIN test_customkeymapping ckm
ON cd.[key] = ckm.customkey
GROUP BY c.ID, c.Name';
EXECUTE SP_EXECUTESQL @SQL;