Solved

Dynamic Pivot Select

Posted on 2014-03-07
4
298 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
  • 2
  • 2
4 Comments
 
LVL 40

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 40

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

760 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now