Solved

SQL Flatten Table Rows Into Single Row /Multiple Columns?

Posted on 2014-01-23
7
5,373 Views
Last Modified: 2014-01-23
I found this link about 'Flattening' rows into columns, just not sure how to apply it to my need here: http://ryanfarley.com/blog/archive/2005/02/17/1712.aspx

[Current Result]
I have a query which returns like this:

Select Code, Name, Price from Products

Code      Name      Price
3262      Jim         NULL
1234      Jim         NULL
9042      Paul       2.000
9999      Paul       2.000
1786      Lou        3.000
2426      Dave      5.000

[Needed Result]
Which needs inserted into a table like so:

row1 ->    3262-Jim   1234-Jim   9042-Paul   9999-Paul  1786-Lou   2426-Dave
row2 ->        na              na            2.000            2.000         3.000          5.000

This table data will be inserted into a much larger table
0
Comment
Question by:WorknHardr
  • 4
  • 3
7 Comments
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 39802903
It appears you want a PIVOT of the data.  I believe the other method was getting you the data in a comma-delimited string whereas you want to insert this into a table (although, are you sure your columns will include code and name).  Anyway, the difficulty with PIVOT in MS SQL is it requires a hard-coded list of values.  However, using dynamic SQL, you can get around this.

Hence, please take a look at the following articles by Mark Wills:
-Dynamic Pivot Procedure for SQL Server
-Dynamic Pivot Procedure without the Pivot function

Once you have the PIVOT procedure in place, you could create a view of your data that prepares it for the pivot.

e.g.
CREATE VIEW products_to_pivot AS
SELECT PivotColumn = Code+'-'+Name
     , ValueColumn = Price 
FROM Products
;

Open in new window


I hope that helps!

Kevin
0
 

Author Comment

by:WorknHardr
ID: 39802998
Hmmm, how do I 'call' the view without getting this error:

    Error: "Conversion failed when converting the varchar value '9041-' to data type int."

Note: the 'Code' column is type INT

I thought maybe I needed to Cast the INT to Varchar in the View, but that doesn't work..

--CREATE
Alter VIEW products_to_pivot
AS
SELECT PivotColumn = Cast(Code as Varchar(10)) + '-' + [Name], ValueColumn = Price
FROM Products
0
 
LVL 59

Expert Comment

by:Kevin Cross
ID: 39803040
Sorry, I forgot about the code being INT.  You do need to convert it.  What you have should have worked, but try with CONVERT.
ALTER VIEW products_to_pivot AS
SELECT PivotColumn = CONVERT(VARCHAR(10), Code)+'-'+Name
     , ValueColumn = Price 
FROM Products
;

Open in new window

0
Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

 

Author Comment

by:WorknHardr
ID: 39803180
I found this Pivot link: http://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx

Q. Why don't I see Pivot in you code above?
0
 
LVL 59

Accepted Solution

by:
Kevin Cross earned 500 total points
ID: 39803276
That is the Technet article I pointed you to in my initial comment.  Ultimately, you need PIVOT; however, because you want this dynamic, you have to use code like Mark explains.  I opted not to retype it here as you will need to understand it, or at least implement his stored procedure anyway.  After you do, you will see that you need to pass it a view, the pivot column, and the value column names.  Basically, the view you created here will work with the dynamic stored procedure from Mark's article without much extra work on your part.  If you do not have the ability to use PIVOT, or otherwise meet criteria Mark speaks of in the second article, you can use the second stored procedure.

Therefore, start with the articles and understand PIVOT, then leverage this view.

I hope that makes sense.
0
 

Author Comment

by:WorknHardr
ID: 39803436
got it, thx
0
 

Author Closing Comment

by:WorknHardr
ID: 39803823
Thanks for getting on-track :)
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

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 …
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…
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

930 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

12 Experts available now in Live!

Get 1:1 Help Now