Solved

Convert rows into Columns in SQL Server, T-SQL

Posted on 2016-09-01
5
115 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
[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
  • 3
  • 2
5 Comments
 
LVL 49

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 49

Expert Comment

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

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

Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

Question has a verified solution.

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

Introduction SQL Server Integration Services can read XML files, that’s known by every BI developer.  (If you didn’t, don’t worry, I’m aiming this article at newcomers as well.) But how far can you go?  When does the XML Source component become …
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

690 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