[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 520
  • Last Modified:

Multiple rows to single row with multiple columns

I have a table that has information for users associated with the same company on MS SQL 2005

CompanyID | Name   |  Address  |  City   | State   |   Zip   |  Phone
         2          Name1    Address1   City1   State1    Zip1    phone1
         2          Name2    Address2  City2   State2    Zip2    phone2
         3          Name3    Address3  City3   State3    Zip3    phone3

I need to grab the users on the same company and return the data on a single row as follows

Name1 | Address1 | City1 | State1 | Zip1 |  Name2 | Address2 | City2 | State2 |  Zip2
Name1   Address1   City1   State1   Zip1   Name2   Address2   City2   State2   Zip2

Notice that the column names are numbered.
Is it possible to create a query to dynamically generate the column names with a number depending on the number of users associated to the company id (no more than 5 per company) and have a single row with all the results?

This is needed to populate a PDF that only accepts 1 row results from the query. the PDF has fields

Name1    Address1   City1   State1    Zip1    phone1
Name2    Address2  City2   State2    Zip2    phone2

Any help will be greatly appreciated.
0
Benjamin_
Asked:
Benjamin_
1 Solution
 
dbaSQLCommented:
Not sure if this is exactly what you're looking for, but.... it works.
There are a couple very good single-line result set examples here:  http://www.sqlfingers.com/p/tsql-tips.html
--create table with your data
create table company (companyID int, name varchar(15),Address varchar(35),City varchar(20),State char(6),zip char(6),phone varchar(10))
insert company (companyID,name,Address,City,State,zip,phone)
select 2,'Name1','Address1','City1','State1','Zip1','phone1'
union
select 2,'Name2','Address2','City2','State2','Zip2','phone2'
union
select 3,'Name3','Address3','City3','State3','Zip3','phone3'

--check data, make sure it's good
select * from company

--get back records for the same companyID in one line
SELECT 
    a.name [Name1],a.Address [Address1],a.City [City1],a.state [State1],a.zip [Zip1],
    b.name [Name2],b.Address [Address2],b.City [City2],b.state [State2],b.zip [Zip2]
FROM 
    dbo.Company a INNER JOIN dbo.company b
     ON a.companyID = b.companyID
     AND (a.name < b.Name)

--result
Name1	Address1	City1	State1	Zip1  	Name2	Address2	City2	State2	Zip2

Open in new window

0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now