Solved

Convert Columns to Rows with a View

Posted on 2011-09-30
6
191 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
Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

 
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

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Question has a verified solution.

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

The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
I have a large data set and a SSIS package. How can I load this file in multi threading?
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

867 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

24 Experts available now in Live!

Get 1:1 Help Now