Solved

Convert rows into Columns in SQL Server, T-SQL

Posted on 2016-09-01
5
67 Views
Last Modified: 2016-09-13
Hi Guys,
I need to convert rows into columns. My requirement is that a postcode can have several addresses like below.

AB1 2DE , Address 1
AB1 2DE, Address 2
AB1 2DE, Address 3
.................................
.................................
AB1 2DE, Address N
AB2 1DE, Address 1
''''''''''''''''''''''''''''''''''''''''
AB2 1DE, Address N

I want to display all the addresses of a postcode as columns
AB12DE Address1 Address2 Address3 .........................Address N
AB2 1DE Address1 Address2 Address3 .........................Address N

Please note i am using SQL Server 2014

Kindest regards
0
Comment
Question by:shah36
  • 3
  • 2
5 Comments
 
LVL 48

Accepted Solution

by:
PortletPaul earned 500 total points
ID: 41779706
ALL addresses of a postcode as columns......
What is the maximum number of addresses you have to deal with?

select max(n) as maxnum
from (
    select postcode, count(*) as n from yourtable group by postcode
   ) d

Only if that number is reasonably small should you "pivot" rows into columns
i.e. if maxnum is hundreds or thousands would you really want to try it?

You need "dynamic sql" to achieve what you want, e.g.

DECLARE @cols AS nvarchar(max)
DECLARE @query AS nvarchar(max)

SET @cols = STUFF((
      SELECT DISTINCT
            ',' + QUOTENAME(address)
      FROM yourtable
      FOR xml PATH (''), TYPE
)
.value('.', 'NVARCHAR(MAX)')
, 1, 1, '')

SET @query = 'SELECT postcode, ' + @cols + ' FROM
                (
                    SELECT
                          postcode, address
                     FROM yourtable
               ) sourcedata
                pivot
                (
                     max([address])
                    FOR [address] IN (' + @cols + ')
                ) p '

--SELECT @query /* use select to inspect the generated sql */

-- EXECUTE(@query) /*once satisfied that sql is OK, use execute (INSTEAD) */

Open in new window

0
 

Author Comment

by:shah36
ID: 41786118
Thanks a lot it helps
0
 
LVL 48

Expert Comment

by:PortletPaul
ID: 41786961
Great! Will you close off the question please?
0
 
LVL 48

Expert Comment

by:PortletPaul
ID: 41795130
Thank you. Closure of questions is really appreciated.

Cheers
Paul
0
 

Author Comment

by:shah36
ID: 41796034
You are welcome Paul and really sorry i did not realise that i had not closed the question.

regards
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties

939 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

6 Experts available now in Live!

Get 1:1 Help Now