我在执行查询时遇到此错误 为“ stat”多次指定了“ 30”列。
FROM Probale
--WHERE (EntryDate BETWEEN @StartDate AND @Enddate)
ORDER BY EntryDate
DECLARE @cols NVARCHAR(4000)
SELECT @cols = COALESCE(@cols + ',[' + CONVERT(varchar, DATEPART(DAY, EntryDate), 112)
+ ']','[' + CONVERT(varchar,DATEPART(DAY, EntryDate), 112) + ']')
FROM #Dates24
ORDER BY EntryDate
DECLARE @qry NVARCHAR(4000) =
N'SELECT *
FROM (SELECT ItemMasterFile.Descriptionitem,Probale.prdqty,
DATEPART(DAY, Probale.EntryDate)as DDate
FROM Probale Inner Join ItemMasterFile on Probale.Codeitem=ItemMasterFile.Codeitem )prd
PIVOT (Sum(prdqty) FOR DDate IN (' + @cols + ')) AS stat
'
-- Executing the query
EXEC(@qry)```
答案 0 :(得分:2)
您的列名称应该是唯一的。您可以尝试使用此作为列名。
SELECT @cols = @cols + ',' + QUOTENAME( CONVERT(varchar(2),EntryDate) )
FROM (SELECT DISTINCT DATEPART(DAY, EntryDate) AS EntryDate FROM #Dates24 ) T
ORDER BY EntryDate
SET @cols = STUFF(@cols, 1, 1, '')