Hi,
I wanted to make a pivot on two columns in the sql server table which will have to generate dynamic columns. I have tried in the following way
What I have tried:
CREATE TABLE [dbo].[Test](
[Writer] [nvarchar](300) NULL,
[PackageID] [nvarchar](300) NULL,
[PubType] [nvarchar](300) NULL,
[RFT] [int] NULL,
)
INSERT INTO Test
VALUES
('Ajeeth Kumar','723','ABC',1),
('Ajeeth Kumar','724','ABC',1),
('Ajeeth Kumar','725','ABC',1),
('Ajeeth Kumar','726','DEF',1),
('Ajeeth Kumar','727','DEF',0),
('Ajeeth Kumar','728','DEF',0)
SELECT * FROM Test
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(PubType)
FROM Test
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)') ,1,1,'')
PRINT @cols
SET @query = 'SELECT Writer, ' + @cols + ' from
(
SELECT Writer
,PackageID
,PubType
FROM Test
)x
PIVOT
(
COUNT(PackageID)
for PubType in (' + @cols + ')
)p
WHERE Writer IS NOT NULL'
EXECUTE (@query)
This gives me the out put as i had pivoted only with PubType column
Writer ABC DEF
Ajeeth Kumar 3 3
But i need the output to be pivoted with PubType and RFT column as well so that my output looks like
Writer ABC DEF 0 1
Ajeeth Kumar 3 3 2 4
Any help on this will be appreciated. Thank you!!