Solved

SQL Flatten Table Rows Into Single Row /Multiple Columns?

Posted on 2014-01-23
7
5,298 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
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

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

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Having an SQL database can be a big investment for a small company. Hardware, setup and of course, the price of software all add up to a big bill that some companies may not be able to absorb.  Luckily, there is a free version SQL Express, but does …
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
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 backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

707 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

17 Experts available now in Live!

Get 1:1 Help Now