我想设置一个如下所示的数据透视语句,但我不想传递列值,而是希望它全部返回;我想将底部的括号留空(即 Sum(fldNI) FOR fldCI IN ( )....
SELECT *
FROM
(
SELECT fldPK
,fldFPK
,fldNI
,fldCI
FROM qryOne
) as x
PIVOT
(
Sum(fldNI) FOR fldCI IN ()
) as p
我想设置一个如下所示的数据透视语句,但我不想传递列值,而是希望它全部返回;我想将底部的括号留空(即 Sum(fldNI) FOR fldCI IN ( )....
SELECT *
FROM
(
SELECT fldPK
,fldFPK
,fldNI
,fldCI
FROM qryOne
) as x
PIVOT
(
Sum(fldNI) FOR fldCI IN ()
) as p
当您使用 PIVOT 函数时,必须知道这些值才能将它们转换为列。如果您不提前知道这些值,那么您将不得不实施动态 SQL 来获得结果。动态 SQL 代码将创建将转换为列的值列表,然后将该列表连接到执行的查询字符串。
代码将类似于:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(fldCI)
from qryOne
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT fldPK, fldFPK, ' + @cols + '
from
(
SELECT fldPK
,fldFPK
,fldNI
,fldCI
FROM qryOne
) x
pivot
(
sum(fldNI)
for fldCI in (' + @cols + ')
) p '
execute sp_executesql @query