Solved

SQL Flatten Table Rows Into Single Row /Multiple Columns?

Posted on 2014-01-23
7
5,826 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
[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
  • 4
  • 3
7 Comments
 
LVL 60

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 60

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 60

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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
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 ?
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

734 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