Monday, May 27, 2013

having problem in creating table from another table

TRY THIS,



----------------------------------------
CREATE TABLE depottable (depot_id int,depot_name nvarchar(10))
INSERT INTO depottable VALUES(1,'A')
INSERT INTO depottable VALUES(2,'B')
INSERT INTO depottable VALUES(3,'C')
------------------------------------------ PIVOT CMD
DECLARE
@cols nvarchar(max),
@stmt nvarchar(max)
SELECT @cols = isnull(@cols + ', ', '') + '[' + T.depot_name + ']' FROM (SELECT distinct depot_name FROM depottable) as T
PRINT @cols
SET @stmt= 'SELECT TOP 0 * INTO NEWTABLE FROM (SELECT * from depottable) x
PIVOT
(
count(depot_name) FOR depot_name in (' + @cols + ')
) AS pvt'
EXEC sp_executesql @stmt = @stmt
---------------------------------------------- FINAL QUERY
SELECT * FROM NEWTABLE
----------------------------------------------
DROP TABLE depottable
DROP TABLE NEWTABLE





Regards, RSingh


No comments:

Post a Comment