Solved

SQL Flatten Table Rows Into Single Row /Multiple Columns?

Posted on 2014-01-23
7
5,573 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
Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

 

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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
SQL STANDARD CORE 6 29
SQL Server 2012 Database Restore 4 38
Need help with T-SQL on SQL Server 2014 9 37
SQL Group By Question 4 18
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 …
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Viewers will learn how the fundamental information of how to create a table.

789 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