Solved

Convert Columns to Rows with a View

Posted on 2011-09-30
6
196 Views
Last Modified: 2012-05-12
Hello all,
I have a table with this data:

Batch      Element      Value
1      Carbon      52
1      Oxy      12
1      Nit      14
2      Carbon      33
2      Oxy      5

What I need is a View that will convert the data to:

For Batch 1
Batch      Carbon      Oxy      Nit
1      52      12      14

For Batch 2
Batch       Carbon      Oxy
2      33      5


I can only link my data in my ERP system to an SQL View.
 My problem is that with different batchs, different elements are measured.  There are about 7000 Batches.  I cant return Elements with Null values.  I have to return integers.  I can limit the number of columns to about 30.  The ERP System can be most difficult.  What makes this worse is that its an Industry Specific Quality Document.

To get the results in a view I am thinking maybe I would need to use an SQL Function.  Then I worry about performance.  I have thought about this for two years and I am clueless where to start.  thanks in advance.  


0
Comment
Question by:sqlguy29
[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
  • 3
  • 2
6 Comments
 
LVL 60

Accepted Solution

by:
Kevin Cross earned 500 total points
ID: 36894990
Hi.

MS SQL 2005 and higher has e PIVOT keyword that may help with this. The caveat is that it requires a finite, static lost of data values to pivot on. It appears that is the case you have here, so you can give that a try.

The basic syntax is:
SELECT *
FROM your_table
PIVOT (SUM(Value) FOR Element IN (Carbon, Oxy, Nit)) pvt
;

You can explicitly define the columns in the select statement, so you can do COALESE(Carbon, 0) so you can get zeros instead of NULL.

Hope that helps!
0
 
LVL 22

Expert Comment

by:Thomasian
ID: 36895325
You can use dynamic sql to return different columns for each batch
CREATE TABLE #t (Batch int, Element varchar(20), Value int)

INSERT #t			--Insert test data
SELECT 1,'Carbon',52
UNION ALL SELECT 1,'Oxy',12
UNION ALL SELECT 1,'Nit',14
UNION ALL SELECT 2,'Carbon',33
UNION ALL SELECT 2,'Oxy',5

DECLARE @batch int	--batch number to query
SET @batch=2

DECLARE @elements varchar(max)	--list of elements for batch
SET @elements= STUFF((SELECT ','+QUOTENAME(Element) FROM #t WHERE Batch=@batch FOR XML PATH ('')),1,1,'')

DECLARE @sql varchar(max)	--dynamic sql statement
SET @sql =
'SELECT *
FROM #t
PIVOT (SUM(Value) FOR Element IN (' + @elements  + ')) pvt
WHERE Batch=' + CAST(@batch as varchar) 

print @sql	--print the sql statement for debugging
exec (@sql)

GO

DROP TABLE #t	--drop test table

Open in new window

0
 
LVL 60

Assisted Solution

by:Kevin Cross
Kevin Cross earned 500 total points
ID: 36895331
You cannot use dynamic SQL in a view. ;)
0
Veeam gives away 10 full conference passes

Veeam is a VMworld 2017 US & Europe Platinum Sponsor. Enter the raffle to get the full conference pass. Pass includes the admission to all general and breakout sessions, VMware Hands-On Labs, Solutions Exchange, exclusive giveaways and the great VMworld Customer Appreciation Part

 
LVL 22

Expert Comment

by:Thomasian
ID: 36895334
aah, I missed that part. :)
0
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 36895364
I figured, but it is good you showed it in case the view is not really a hard requirement. I was just pointing that out before getting the post back that it errored out in the view. Which would be interesting if the ERP application could take variable columns and handle well versus fixed number with 0's when not applicable. I had one system like that where you can store variable length fields -- those are pain to do reporting on -- well if you have users who are very inconsistent about where they put data as I would always get one value of "." because they did not want to fill in the field, so now it thinks there are multiple values in the field. *sigh* Anyway, I digress. Hopefully, this is helpful to sqlguy29!
0
 

Author Closing Comment

by:sqlguy29
ID: 37031649
I didnt use this solution be appreciate the effort.   I just split the points. Thanks guys
0

Featured Post

Independent Software Vendors: 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

Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

617 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