Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

Changing columns to rows.

Total Hit ( 1465)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


Another example that shows how to convert columnar values into individual rows.

Click here to copy the following block
CREATE TABLE #Classes (
Name  varchar( 30 ) ,  
Class1  varchar( 30 ) ,  
Class2  varchar( 30 ) ,  
Class3 varchar( 30 )
);

INSERT INTO #Classes VALUES( 'Steve' , 'Math' , 'Calc' , 'Calc2' );
INSERT INTO #Classes VALUES( 'Peter' , 'English' , NULL , 'Chinese' );
SELECT * FROM #Classes;
/*
Name  Class1  Class2 Class3            
------ -------- ------- ------------------------------
Steve Math   Calc  Calc2
Peter English NULL  Chinese
*/

GO

-- Objective:
-- To use the denormalized table and
-- get the classes as rows for each student.
SELECT *
FROM (
SELECT Name , CASE ClassNo
        WHEN 1 THEN Class1
        WHEN 2 THEN Class2
        WHEN 3 THEN Class3
       END AS Classes
FROM #Classes
CROSS JOIN
(
SELECT 1 AS ClassNo UNION ALL SELECT 2 UNION ALL SELECT 3) AS n
) AS c
WHERE classes IS NOT NULL;
/*
Name              Classes            
------------------------------ ------------------------------
Steve             Math
Steve             Calc
Steve             Calc2
Peter             English
Peter             Chinese
*/

-- or a UNION ALL query. This is slower in MS SQL Server b'cos
-- the optimizer doesn't handle the same table specified in the
-- different SELECT statements efficiently.
SELECT Name , Class1 AS Classes FROM #Classes WHERE Class1 IS NOT NULL
UNION ALL
SELECT Name , Class2 FROM #Classes WHERE Class2 IS NOT NULL
UNION ALL
SELECT Name , Class3 FROM #Classes WHERE Class3 IS NOT NULL;
GO


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.