Solved

Convert Columns to Rows with a View

Posted on 2011-09-30
6
190 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
  • 3
  • 2
6 Comments
 
LVL 59

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 59

Assisted Solution

by:Kevin Cross
Kevin Cross earned 500 total points
ID: 36895331
You cannot use dynamic SQL in a view. ;)
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 22

Expert Comment

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

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

Backup Your Microsoft Windows Server®

Backup all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

Join & Write a Comment

Suggested Solutions

Introduced in Microsoft SQL Server 2005, the Copy Database Wizard (http://msdn.microsoft.com/en-us/library/ms188664.aspx) is useful in copying databases and associated objects between SQL instances; therefore, it is a good migration and upgrade tool…
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
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 different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed

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

15 Experts available now in Live!

Get 1:1 Help Now