0

我一直在尝试将行转换为 SQL 中的列。

像这样:

|*Name*|*Permissions*|
|App1  |Permission 1 |
|App1  |Permission 2 |
|App1  |Permission 3 |
|App2  |Permission 1 |
|App2  |Permission 2 |
|App2  |Permission 3 |

对此:

|*Name*|*Permission1*|*Permission2*|*Permission3*|
|App1  |Permission 1 |Permission 2 |Permission 3 |
|App2  |Permission 1 |Permission 2 |Permission 3 |

因此我一直在使用类似这样的代码来动态生成查询

declare @permission_id as VARCHAR(7);
declare @counter as int;
declare @query as VARCHAR(MAX);
declare @name as VARCHAR(15);

set @permission_id = 'permission_';
set @query = 'SELECT a.title, ';
set @counter = 0;

WHILE @counter < 3
BEGIN
    PRINT @counter;
    SET @counter = @counter + 1;
    SET @name = (SELECT CONCAT(@permission_id, @counter));
    SET @query = @query + ' select max(case when seqnum = '
    SET @query = (SELECT CONCAT(@query, @counter))
    SET @query = @query + ' then a.permission end) as '
    SET @query = (SELECT CONCAT(@query, @name))

END

生成这样的查询:

select a.name,
       max(case when seqnum = 1 then a.permission end) as permission_1,
       max(case when seqnum = 2 then a.permission end) as permission_2,
       max(case when seqnum = 3 then a.permission end) as permission_3
from (select a.*,
             row_number() over (partition by a.name order by a.name) as seqnum
      from apps a
     ) a
group by a.name;

结果对于最多 120 个权限工作正常,因为这是查询超过 varchar 最大长度的点。

在不连接查询的情况下,我还没有找到动态旋转的解决方案,也没有找到更长查询的解决方案。

这就是我问这个问题的原因。

有没有办法在没有 CONCAT 查询的情况下进行动态透视,或者有什么我可以使用的东西来代替 varchar?

谢谢!

4

0 回答 0