Click here to Skip to main content
15,887,924 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a table as below

TName Scode
AKAT Allow1
AKAT Allow2
AKAT Allow3
AKAT Allow4
AkCT Allow1
AKCT Allow2
AKCT Allow3
AKST Allow1
AKST Allow2
AKST Allow3
AKST Allow4
AKST Allow5
. .
. .
. .


I want a result as below:

AKAT AKCT AKST . . .
Allow1 Allow1 Allow1 . . .
Allow2 Allow2 Allow2 . . .
Allow3 Allow3 Allow3 . . .
Allow4 Allow4 .
Allow5

What I have tried:

I have tried multiple queries by googling but none have helped.

There can be many Tnames so i cannot have a static query. and the fields are varchar datatype so not sure if aggregate can be used.

I can add a TID column in the table as numeric field but those TID's will be same for particular Tname. if thats helpful in querying.
Posted
Updated 17-May-17 6:25am

1 solution

Check this:
SQL
CREATE TABLE #tmp (TName VARCHAR(30), Scode VARCHAR(30))

INSERT INTO #tmp(TName, Scode)
VALUES('AKAT', 'Allow1'),
('AKAT', 'Allow2'),
('AKAT', 'Allow3'),
('AKAT', 'Allow4'),
('AkCT', 'Allow1'),
('AKCT', 'Allow2'),
('AKCT', 'Allow3'),
('AKST', 'Allow1'),
('AKST', 'Allow2'),
('AKST', 'Allow3'),
('AKST', 'Allow4'),
('AKST', 'Allow5')

DECLARE @cols NVARCHAR(4000) = STUFF((SELECT DISTINCT '],[' + TName
				FROM #tmp
				ORDER BY '],[' + TName
				FOR XML PATH('')) , 1, 2, '') + ']'

--SELECT @cols

DECLARE @Qry NVARCHAR(MAX) = N'
SELECT RowNo, ' + @cols +
'FROM (
	SELECT ROW_NUMBER() OVER(PARTITION BY TName ORDER BY Scode) As RowNo, *
	FROM #tmp
	) dt
PIVOT (MAX(Scode) FOR TName IN(' + @cols + ')) pvt'

EXEC(@Qry)

DROP TABLE #tmp


Result:
RowNo	AKAT	AkCT	AKST
1		Allow1	Allow1	Allow1
2		Allow2	Allow2	Allow2
3		Allow3	Allow3	Allow3
4		Allow4	NULL	Allow4
5		NULL	NULL	Allow5
 
Share this answer
 
Comments
akarsha 17-May-17 21:49pm    
Thanks so much. It worked exactly the way I wanted :).
Maciej Los 18-May-17 1:43am    
You're very welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900