SQL Creating Dynamic columns

Hello,
How can I change this

Usage      Capacity      ControllerDnsName      RegistrationStateChangeDate
3              10            CONTROLLER1            2015-02-24
7              10            CONTROLLER2            2015-02-24
1              10            CONTROLLER1            2015-11-07
1              10            CONTROLLER1            2015-11-08
1              10            CONTROLLER1            2015-11-10
1              10            CONTROLLER1            2015-11-11
6              10            CONTROLLER1            2015-11-13

To this via SQL
Controller1-Usage      Controller-2Usage      Capacity      RegistrationStateChangeDate
3                                                  7                  10            2015-02-24
1                                                  0                  10            2015-11-07
1                                                  0                  10            2015-11-08
1                                                  0                  10            2015-11-10
1                                                  0                  10            2015-11-11
6                                                  0                  10            2015-11-13
LVL 4
Mauro CazabonnetSenior .NET Software EngineerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Brian CroweDatabase AdministratorCommented:
DECLARE @Test TABLE
(
	Usage						INT,
	Capacity					INT,
	ControllerDnsName			VARCHAR(50),
	RegistrationStageChangeDate	DATE
);

INSERT INTO @Test (Usage, Capacity, ControllerDnsName, RegistrationStageChangeDate)
VALUES
	(3, 10, 'CONTROLLER1', '2015-02-24'),
	(7, 10, 'CONTROLLER2', '2015-02-24'),
	(1, 10, 'CONTROLLER1', '2015-11-07'),
	(1, 10, 'CONTROLLER1', '2015-11-08'),
	(1, 10, 'CONTROLLER1', '2015-11-10'),
	(1, 10, 'CONTROLLER1', '2015-11-11'),
	(6, 10, 'CONTROLLER1', '2015-11-13');

SELECT ISNULL(CONTROLLER1, 0) AS [Controller1-Usage],
	ISNULL(CONTROLLER2, 0) AS [Controller2-Usage],
	Capacity,
	RegistrationStageChangeDate
FROM
(
	SELECT Usage, Capacity, ControllerDnsName, RegistrationStageChangeDate
	FROM @Test
) AS Src
PIVOT
(
	MAX(Usage)
	FOR ControllerDnsName IN (CONTROLLER1, CONTROLLER2)
) AS Pvt

Open in new window


Output:

Controller1-Usage	Controller2-Usage	Capacity	RegistrationStageChangeDate
3	7	10	2015-02-24
1	0	10	2015-11-07
1	0	10	2015-11-08
1	0	10	2015-11-10
1	0	10	2015-11-11
6	0	10	2015-11-13

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Kevin CrossChief Technology OfficerCommented:
Please credit Brian on this as I like the PIVOT solution.  Note, though, if you have multiple rows with each controller, it may be appropriate to SUM in the PIVOT.  Subsequently, if you only ever have two columns, it may be just as easy to use a solution like this.

SELECT [Controller1-Usage] = SUM(CASE ControllerDnsName WHEN 'CONTROLLER1' THEN Usage ELSE 0 END)
     , [Controller2-Usage] = SUM(CASE ControllerDnsName WHEN 'CONTROLLER2' THEN Usage ELSE 0 END)
     , Capacity
     , RegistrationStageChangeDate
FROM (
	VALUES
		(3, 10, 'CONTROLLER1', '2015-02-24'),
		(7, 10, 'CONTROLLER2', '2015-02-24'),
		(1, 10, 'CONTROLLER1', '2015-11-07'),
		(1, 10, 'CONTROLLER1', '2015-11-08'),
		(1, 10, 'CONTROLLER1', '2015-11-10'),
		(1, 10, 'CONTROLLER1', '2015-11-11'),
		(6, 10, 'CONTROLLER1', '2015-11-13')
) your_table(Usage, Capacity, ControllerDnsName, RegistrationStageChangeDate)
GROUP BY Capacity, RegistrationStageChangeDate
;

Open in new window


Again, Brian's answer is correct.  This is just an FYI for others who maybe cannot use PIVOT.
Mauro CazabonnetSenior .NET Software EngineerAuthor Commented:
Brian how can create the columns dynamically
based on the distinct list of controllers rather than hard coding controller names

SELECT  @COLS = STUFF((SELECT DISTINCT ',' + QUOTENAME(ControllerDnsName)
FROM @Test
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
IT Pros Agree: AI and Machine Learning Key

We’d all like to think our company’s data is well protected, but when you ask IT professionals they admit the data probably is not as safe as it could be.

Mauro CazabonnetSenior .NET Software EngineerAuthor Commented:
Work in progress
DECLARE @cols as NVARCHAR(MAX), @colsRollUp nvarchar(max), @query  AS NVARCHAR(MAX)


CREATE TABLE Test
(
      Usage                                    INT,
      Capacity                              INT,
      ControllerDnsName                  VARCHAR(50),
      RegistrationStateChangeDate      DATE
);


INSERT INTO TEST (Usage, Capacity, ControllerDnsName, RegistrationStateChangeDate)
VALUES
      (3, 10, 'CONTROLLER1', '2015-02-24'),
      (7, 10, 'CONTROLLER2', '2015-02-24'),
      (1, 10, 'CONTROLLER1', '2015-11-07'),
      (1, 10, 'CONTROLLER1', '2015-11-08'),
      (1, 10, 'CONTROLLER1', '2015-11-10'),
      (1, 10, 'CONTROLLER1', '2015-11-11'),
      (6, 10, 'CONTROLLER1', '2015-11-13');

SELECT  @COLS = STUFF((SELECT DISTINCT ',' + QUOTENAME(ControllerDnsName)
FROM Test
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')

set @query = 'SELECT ' + @cols + ' capacity, RegistrationStateChangeDate from
      (
            SELECT Usage, Capacity, ControllerDnsName, RegistrationStateChangeDate
                  FROM Test
) AS Src
PIVOT
(
      MAX(Usage)
      FOR ControllerDnsName IN (' + @cols + ')
) AS Pvt'

execute (@query)
Brian CroweDatabase AdministratorCommented:
You're on the right track with the dynamic pivot.  You will want to use sp_executesql instead of the EXECUTE(@query) though.

http://blogs.msdn.com/b/turgays/archive/2013/09/18/exec-vs-sp-executesql.aspx
Mauro CazabonnetSenior .NET Software EngineerAuthor Commented:
Can use some guidance..

DECLARE @DynamicPivotQuery as NVARCHAR(max)
DECLARE @ColumnName as NVARCHAR(MAX)

--Get Distinct values of the Pivot Column
SELECT @ColumnName = ISNULL(@ColumnName + ',','') + QUOTENAME(ControllerDnsName)
FROM (SELECT DISTINCT ControllerDnsName from Test) as ControllerDnsName

SET @DynamicPivotQuery =
N'SELECT usage, capacity, ' + @ColumnName + ', RegistrationStateChangeDate
FROM TEST
PIVOT (MAX(Usage)
      FOR ControllerDnsName IN (' + @ColumnName + ')) as PVTTable'
EXEC sp_executesql @DynamicPivotQuery
Mauro CazabonnetSenior .NET Software EngineerAuthor Commented:
I think I got it...

DECLARE @DynamicPivotQuery as NVARCHAR(max)
DECLARE @ColumnName as NVARCHAR(MAX)

--Get Distinct values of the Pivot Column
SELECT @ColumnName = ISNULL(@ColumnName + ',','') + ControllerDnsName
FROM (SELECT DISTINCT ControllerDnsName from Test) as ControllerDnsName


SET @DynamicPivotQuery =
N'SELECT ' + @ColumnName + ', Capacity, RegistrationStateChangeDate
FROM TEST
PIVOT (MAX(Usage)
      FOR ControllerDnsName IN (' + @ColumnName + ')) as PVTTable'


EXEC sp_executesql @DynamicPivotQuery
Brian CroweDatabase AdministratorCommented:
That should work.  It typically takes a little trial and error to get a dynamic sql query like this to work and you can preview it by using PRINT right before your EXECUTE to look at the query.  Most of the time it is issues with getting the quotes correct since you need to embed two single-quotes to get one single-quote.
Mauro CazabonnetSenior .NET Software EngineerAuthor Commented:
Thx!!!!!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2008

From novice to tech pro — start learning today.