Solved

Dynamic Pivot Select

Posted on 2014-03-07
4
308 Views
Last Modified: 2014-03-11
I have been struggling with this.

I use a dynamic select list of fields that I then use to get data on.
e.g. SELECT FieldName FROM MandatoryTable
Result in comma delimited list = 'Date of Incorporation','Country of Incorporation' etc etc.

I then SELECT the data against a "Client" table for the these fields leading with a primary key.
Record set = 'Client1','2013-02-01','England'
Client2,Null,'France'
etc
etc

What I actually want is the result set to be sent to a table or temp table and to be pivoted;
Columns would be: ClientID / FieldName / FieldValue
Record Set; 'Client1', 'Date of Incorporation', '2013-02-01'
'Client2','Date of Incorporation','Null'
etc
etc

I am currently stuck with this code;

DECLARE
      @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

-- GET LIST OF DYNAMIC FIELDS TO PASS TO FINAL SELECT
select @cols = STUFF(
                  (
                        SELECT
                              distinct ',' + QUOTENAME(REPLACE(TFN.[FieldName],'''','_'))
                    FROM
                                    [ChangeLogFields] AS CLS
                              JOIN
                                    [TableFieldNames] AS TFN
                                    ON TFN.[TableNo] = CLS.[Table No_]
                                    AND TFN.[FieldNo] = CLS.[Field No_]
                              WHERE
                                    TFN.[TableName] = 'Client'
                                    AND CLS.[Mandatory] <> 0
                              
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

-- SET QUERY TO EXECUTE AND PIVOT
set @query = '
            (
                  SELECT
            [Client No_],
                  ' + @cols + '
            FROM
                        Client
         )
           PIVOT
           (
                  [FieldName]
                  FOR [Client No_]  
                  IN ' + @cols + '
           ) AS PivotTable
            '
           
execute(@query);

Thanks in advance.
0
Comment
Question by:BrightRaven
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 41

Expert Comment

by:Sharath
ID: 39913633
I think you need an Unpivot here. Try this if this gives what you are looking for Date and Country columns.
 If this is your expected output, you can replace the columns list with a variable and execute the query dynamically.
 SELECT [Client No_],FieldName,FieldValue
   FROM Client
UNPIVOT (FieldValue FOR FieldName IN ([Date of Incorporation],[Country of Incorporation])) P

Open in new window

0
 

Author Comment

by:BrightRaven
ID: 39917071
Thanks for response Sharath.

FieldName and FieldValue do not exist in the table Client? Not sure how this works!
0
 
LVL 41

Accepted Solution

by:
Sharath earned 500 total points
ID: 39919013
check this
 SELECT [Client No_],FieldName,FieldValue
   FROM (select [Client No_],
                convert(varchar(20),[Date of Incorporation]) 'Date of Incorporation',
				[Country of Incorporation]
           from Client) T1
UNPIVOT (FieldValue FOR FieldName IN ([Date of Incorporation],[Country of Incorporation])) P

Open in new window

http://sqlfiddle.com/#!3/959bf/5
0
 

Author Closing Comment

by:BrightRaven
ID: 39920737
Although not the full final solution. It steered me to it. Thank you.
0

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article I will describe the Detach & Attach method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question