我目前有以下脚本将结果从行转换为列。除了两个问题外,它的作品很棒;
我在另一个表中有一个标志,我想过滤它(基本上是:WHERE Table.Stats=YES
)。我通常在基本查询中执行此操作,内部连接后跟WHERE语句。在下面的查询中,我已经有了WHERE FileSeq=25
,但是我需要工作的这个标准是调用另一个表。
查询返回了许多不确定的NULL字段。
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SELECT @cols = STUFF((SELECT ',' + QUOTENAME(col+CAST(rn AS varchar(6)))
FROM
(
SELECT row_number() over(partition by UID ORDER BY ClassCode) rn
FROM dbo.StudentClasses
) d
CROSS APPLY
(
SELECT 'ClassCode', 1
) c (col, so)
GROUP BY col, rn, so
ORDER BY rn, so
FOR XML PATH(''), TYPE
).VALUE('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT UID,' + @cols + '
FROM
(
SELECT UID, col+CAST(rn AS varchar(10)) col, VALUE
FROM
(
SELECT UID, classcode,
row_number() over(partition by UID ORDER BY classcode) rn
FROM StudentClasses WHERE FileSeq=25
) t
CROSS APPLY
(
SELECT ''classcode'', CAST(classcode AS varchar(6))
) c (col, VALUE)
) x
PIVOT
(
MAX(VALUE)
for col in (' + @cols + ')
) p '
EXECUTE(@query)
任何帮助表示赞赏