且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过组合 2 列形成新列,将 SQL Server 中的行转换为列

更新时间:2023-02-07 13:41:00

您需要在旋转之前计算子查询中的年/季度字符串.我认为你想要的逻辑是:

You need to compute the year/quarter string in the subquery before pivoting. I think the logic you want is:

set @query = 
    n'select ' + @cols + n' from 
    (
        select [count], 
            convert(nvarchar, [year]) + ''q'' + convert(nvarchar, [quarter]) yyyyqq
        from #yourtable
    ) x pivot (
        max([count])
        for yyyyqq in (' + @cols + n')
    ) p';

exec sp_executesql @query;