我的输入表是
+--------+----------+----------+-------+
| userid | teamname | task1 | task2 |
+--------+----------+----------+-------+
| 101 | T1 | 101task1 | desc1 |
| 101 | T1 | 101task2 | desc2 |
| 101 | T2 | 101task1 | desc3 |
| 101 | T2 | 101task2 | desc4 |
| 101 | T2 | 101task2 | desc5 |
| 102 | T3 | 102task1 | desc6 |
| 102 | T3 | 102task2 | desc7 |
| 102 | T3 | 102task3 | desc8 |
| 102 | T3 | 102task4 | desc9 |
+--------+----------+----------+-------+
我希望输出如下,以枢轴(动态)task1 + task2
+--------+----------+----------------+----------------+----------------+----------------+
| userid | teamname | 1 | 2 | 3 | 4 |
+--------+----------+----------------+----------------+----------------+----------------+
| 101 | T1 | 101task1 desc1 | 101task2 desc2 | | |
| 101 | T2 | 101task1 desc3 | 101task2 desc4 | 101task2 desc5 | |
| 102 | T3 | 102task1 desc6 | 102task2 desc7 | 102task3 desc8 | 102task4 desc9 |
+--------+----------+----------------+----------------+----------------+----------------+
我尝试透视task1,它的工作方式类似于示例代码SampleCode,
但是当我旋转max(task1+task2)
时会出错
答案 0 :(得分:1)
您需要将它们合并到数据透视表的源中,并通过给它们提供别名来使用它们。
set @query = 'SELECT userid,teamname,' + @cols + ' from
(
select userid,
teamname,
concat(task1,task2) as col, --Combine here
ROW_NUMBER() OVER(PARTITION BY userid,teamname order by task1 asc) AS Row#
from #yt
) x
pivot
(
max(col) --Alias used here
for row# in (' + @cols + ')
) p '
execute(@query);
编辑::在字段之间添加空格
set @query = 'SELECT userid,teamname,' + @cols + ' from
(
select userid,
teamname,
CONCAT(task1,SPACE(1),task2) col,
ROW_NUMBER()OVER(PARTITION BY userid,teamname order by task1 asc) AS Row#
from #yt
) x
pivot
(
max(col)
for row# in (' + @cols + ')
) p '
execute(@query);