'How can we use group by keyword on PIVOT table having dynamic column joined with another table or alternative query of Pivot
I have 2 tables named tblDemo and tblSubDemo; tblDemo havve 2 columns _id and _name. tblSubDemo have 3columns, ID,Name, Demo_ID(it is the primary key of tblDemo that is foreign key). Here is my Query:
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX),
@PivotColumnNames AS NVARCHAR(MAX),
@PivotSelectColumnNames AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT @PivotColumnNames= ISNULL(@PivotColumnNames + ',','')
+ QUOTENAME(Name)
FROM (SELECT DISTINCT Name FROM tblSubDemo) AS Names
--Get distinct values of the PIVOT Column with isnullcase when @PivotSelectColumnNames is not Null then 1 end
SELECT @PivotSelectColumnNames
= ISNULL(@PivotSelectColumnNames + ',','')
+ 'ISNULL(' + QUOTENAME(Name) + ', 0) AS '
+ QUOTENAME(Name)
FROM (SELECT DISTINCT Name FROM tblSubDemo) AS Courses
--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =
'SELECT ID, _name, ' + @PivotSelectColumnNames + '
FROM tblSubDemo I
LEFT OUTER JOIN tblDemo M
ON I.Demo_Id = M._id
PIVOT(avg(Demo_ID)
FOR Name IN (' + @PivotColumnNames + ')) AS PVTTable order by _name'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery
it is giving result as enter image description here
What i want is to replace all values greater than 1 to 1 or you can say only 0s and 1s are allowed other 2 and 3 and 4 will be replaced by 1 also.another problem is that about _name column not to repeat same names row by row but group by them according to _name table. this is the image below attached type of result i want enter image description here
this site is not allowing the image to be displayed so please just click the link and see the images
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|