My pivot query is generating duplicate rows, and i'm blocked. can anyone solve this?
我的透视查询正在生成重复的行,我被阻止了。有谁能解决这个问题?
CREATE PROCEDURE [dbo].[test2]
AS
BEGIN
--Declare necessary variables
DECLARE @SQLQuery AS NVARCHAR(MAX);
DECLARE @WeekColumns AS NVARCHAR(MAX);
--Get unique values of pivot column
SELECT @WeekColumns = COALESCE(@WeekColumns + ',', '')
+ QUOTENAME(name)
FROM ( SELECT name
FROM ( SELECT [id_week]
, name
, value
, prjfamilyID
, ROW_NUMBER() OVER ( PARTITION BY name
ORDER BY [id_week] ASC ) rn
FROM weekvalues
) a
WHERE rn = 1
) AS PivotExample;
SELECT @WeekColumns;
--Create the dynamic query with all the values for
--pivot column at runtime
SET @SQLQuery = N'SELECT prjfamilyID, ' + @WeekColumns + '
FROM [dbo].[weekvalues]
PIVOT( MAX(value)
FOR name IN (' + @WeekColumns + ')) AS P';
SELECT @SQLQuery;
--Execute dynamic query
EXEC sp_executesql @SQLQuery;
END;
and Here is the result i am getting
这是我得到的结果
1 NULL NULL 1004 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
1 NULL NULL NULL NULL NULL 997 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
1 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL 992 NULL NULL NULL NULL
1 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL 997
2 NULL NULL 2100 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
2 NULL NULL NULL NULL NULL 2036 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
2 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL 2014 NULL NULL NULL NULL
2 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL 2040
3 NULL NULL 1944 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
3 NULL NULL NULL NULL NULL 1914 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
3 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL 1882 NULL NULL NULL NULL
3 NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL 1880
what i want is for number 1 for example i want to combine all rows in one containing all values
我想要的是1号,例如我想将所有行组合在一起,包含所有值
thanks
谢谢
1 个解决方案
#1
0
Can you change your @SQLQuery
query with this one and try again?
你可以用这个更改你的@SQLQuery查询然后再试一次吗?
SET @SQLQuery =
N'SELECT * FROM (SELECT prjfamilyID, value, name
FROM [dbo].[weekvalues] ) SRC
PIVOT( MAX(value)
FOR name IN (' + @WeekColumns + ')) AS P';
#1
0
Can you change your @SQLQuery
query with this one and try again?
你可以用这个更改你的@SQLQuery查询然后再试一次吗?
SET @SQLQuery =
N'SELECT * FROM (SELECT prjfamilyID, value, name
FROM [dbo].[weekvalues] ) SRC
PIVOT( MAX(value)
FOR name IN (' + @WeekColumns + ')) AS P';