We help IT Professionals succeed at work.

Need help with a Dynamic query and using a Pivot...

101 Views
Last Modified: 2019-01-17
Using SQL Server 2014 and trying to develop a Dynamic query and Pivot.

My input data looks like this:
 InputData.JPG
My desired output looks like this (I'd like it ORDERED BY order_desc):
OutputData.JPG
I want the values under the cnt/number columns to be the "status" field.
If there is some way to add the literal "Kbn" in front of the cnt number in the heading, that would be great too.
NOTE:  In this example these order_desc happens to have 5 cnt columns.   That is not always the case - so it needs to be dynamic.  Sometimes cnt could have 2 or 6 or whatever.
             Although for any given run of the query, I believe all the order_desc in that run will have the same number of cnt columns for each order_desc.

Here is the code I have so far:
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
 
--Get distinct values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
       + QUOTENAME(cnt)
FROM (SELECT DISTINCT cnt FROM #tmpMfgKbn ) AS Kaban
 
--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
  N'SELECT DISTINCT order_desc, ' + @ColumnName + '
    FROM #tmpMfgKbn
    PIVOT(MAX([status]) 
          FOR cnt IN (' + @ColumnName + ')
		  ) AS PVTTable'
		  

--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

Open in new window


Here is the output I am getting:
 OutputBad.JPG
What am I doing wrong?

Thanks
Comment
Watch Question

Mark WillsTopic Advisor, Page Editor
CERTIFIED EXPERT
Distinguished Expert 2018

Commented:
You are trying to pivot directly from the data source. The problem with that is the column [status] has already been transformed into one of the @columnames

Now, I would need to test but something more like :
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
 
--Get values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
       + QUOTENAME(cnt)
FROM (SELECT DISTINCT cnt FROM #tmpMfgKbn GROUP BY order_desc, cnt, [status]) AS Kaban
 
--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
  N'SELECT * FROM
   (SELECT order_desc, [status], CNT
    FROM #tmpMfgKbn ) src
    PIVOT
   (MAX([status]) FOR cnt IN (' + @ColumnName + ')) AS PVTTable'

--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

Open in new window


And of course we can get 'kbn' as a prefix in the header....

One way is to first cast the CNT column as the resulting column name, and has to happen when first building the @columnnames, and then in the SELECT order_desc, [status], CNT  subquery.  In both cases it is a matter of concatenating - easiest to do
'kbn'+ltrim(cnt) as cnt

Open in new window


But would like to type it up with some test data first.

Back in a little while...
Topic Advisor, Page Editor
CERTIFIED EXPERT
Distinguished Expert 2018
Commented:
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION
sqdperuApplication Development Engineer

Author

Commented:
Mark,

Thanks a lot!  That is exactly what I was trying to do.

Here is the output (I changed the order_desc output heading to "Material"):
OutputGood.JPG
Thanks
sqdperuApplication Development Engineer

Author

Commented:
Thanks
Mark WillsTopic Advisor, Page Editor
CERTIFIED EXPERT
Distinguished Expert 2018

Commented:
My pleasure :)

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions