Solved

Dynamic Pivot Select

Posted on 2014-03-07
4
302 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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
SQL Server - Sum Decimal Columns 11 34
SQL Help 27 46
Better way to make a query with date filter. 5 27
PROPERCASE SCRIPT IN SQL 3 7
After restoring a Microsoft SQL Server database (.bak) from backup or attaching .mdf file, you may run into "Error '15023' User or role already exists in the current database" when you use the "User Mapping" SQL Management Studio functionality to al…
Hi all, It is important and often overlooked to understand “Database properties”. Often we see questions about "log files" or "where is the database" and one of the easiest ways to get general information about your database is to use “Database p…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

821 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