我有这张桌子
DECLARE @TreatmentTableVariables TABLE(ParameterCode VARCHAR(64), Value varchar(64))
INSERT @TreatmentTableVariables VALUES ('TripOriginLocationCode','AHO')
INSERT @TreatmentTableVariables VALUES ('TripOriginCountryCode','IT')
SELECT DISTINCT ParameterCode, Value
INTO Staging.tmpParameterCodes
FROM @TreatmentTableVariables;
SET @ParameterCodesToPivot = (SELECT '['+LEFT(ParameterCode, LEN(ParameterCode) - 2)
FROM (
SELECT ParameterCode + '],['
FROM Staging.tmpParameterCodes
where Value IS NOT NULL
FOR XML PATH ('')
) c (ParameterCode)
然后转移代码
SET @sqlquery = '
SELECT *
INTO
Staging.tmpTreatmentInputParameters
FROM
(
SELECT
tip.TreatmentID,
tip.ParameterCode,
tip.ClientCode,
tip.Value
FROM AnalyticsDW.TreatmentInputParameter tip
left join Staging.tmpParameterCodes TPC
on tip.ParameterCode=TPC.ParameterCode
Where
--tip.TreatmentID between @MinTreatmentID and @MaxTreatmentID
--and
TPC.Value IS NOT NULL
and (TPC.Value=tip.Value or TPC.Value='''')
and tip.Value IS NOT NULL
)p
PIVOT
(
MIN(Value)
FOR ParameterCode IN ( '+ @ParameterCodesToPivot +' )
)
AS PVT'
关键是@ParameterCodesToPivot有一个值(TripOriginLocationCode),在AnalyticsDW.TreatmentInputParameter.ParameterCode中不存在。
所以我的结果是TreatmentID,ClientCode,TripOriginCountryCode,TripOriginLocationCode(全部为空),因为AnalyticsDW.TreatmentInputParameter.ParameterCode中没有TripOriginLocationCode的值
数据透视表然后为该列返回null。
因为我正在使用
FOR ParameterCode IN ( '+ @ParameterCodesToPivot +' )
如何将数据库限制为仅创建存在的ParameterCOde列 AnalyticsDW.TreatmentInputParameter
如果需要,我可以创建一些示例数据,只是想知道该特定代码是否期望创建一个空列
答案 0 :(得分:0)
你的一些查询似乎不对,但是......
而不是
SELECT DISTINCT ParameterCode, Value
INTO Staging.tmpParameterCodes
FROM @TreatmentTableVariables;
使用
SELECT DISTINCT
tip.ParameterCode
INTO Staging.tmpParameterCodes
FROM AnalyticsDW.TreatmentInputParameter tip
JOIN Staging.tmpParameterCodes TPC ON tip.ParameterCode = TPC.ParameterCode
WHERE --tip.TreatmentID between @MinTreatmentID and @MaxTreatmentID
--and
TPC.Value IS NOT NULL
AND (TPC.Value = tip.Value
OR TPC.Value = '''')
AND tip.Value IS NOT NULL
这应该只为您提供透视查询中存在的ParameterCodes的列