Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

SQL Flatten Table Rows Into Single Row /Multiple Columns?

Posted on 2014-01-23
7
Medium Priority
?
6,419 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 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
NEW Veeam Backup for Microsoft Office 365 1.5

With Office 365, it’s your data and your responsibility to protect it. NEW Veeam Backup for Microsoft Office 365 eliminates the risk of losing access to your Office 365 data.

 

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 2000 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: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

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

A Stored Procedure in Microsoft SQL Server is a powerful feature that it can be used to execute the Data Manipulation Language (DML) or Data Definition Language (DDL). Depending on business requirements, a single Stored Procedure can return differe…
Microsoft Access has a limit of 255 columns in a single table; SQL Server allows tables with over 255 columns, but reading that data is not necessarily simple.  The final solution for this task involved creating a custom text parser and then reading…
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed

885 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