Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

How convert rows to columns using SQL?

Posted on 2014-09-23
4
Medium Priority
?
167 Views
Last Modified: 2014-09-30
I want to convert rows from the result to column.
Attached Input file is the sample data, I want to the sql server query to return like the result in Result file.
Input.xlsx
Result.xlsx
0
Comment
Question by:Raj G
[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
  • 2
4 Comments
 
LVL 15

Expert Comment

by:Haris Djulic
ID: 40340439
Hi,

you can use this:

select col2, sum(Test1) as Test1, sum(Test2) as Test2, sum(Test3) as Test3
from(
select col2 , 
case when col1='TEST1' then 1 else 0 end as Test1, 
case when col1='TEST2' then 1 else 0 end as Test2, 
case when col1='TEST3' then 1 else 0 end as Test3
from table_name
group by col2 
)a group by col2

Open in new window

0
 
LVL 49

Expert Comment

by:PortletPaul
ID: 40340499
input/resultThis query will match the requested result:
SELECT
        param
      , max(case when col1 = 'TEST1' then col3 end) AS test1
      , max(case when col1 = 'TEST2' then col3 end) AS test2
      , max(case when col1 = 'TEST3' then col3 end) AS test3
FROM Input
CROSS JOIN (SELECT 'COL2' AS param UNION ALL SELECT 'COL3' AS param) cj
GROUP BY
        param
;

Open in new window

But what happens to 'english' as a value from the input table?

{+ edit, details}
    CREATE TABLE Input
    	([COL1] varchar(5), [COL2] varchar(7), [COL3] int)
    ;
    	
    INSERT INTO Input
    	([COL1], [COL2], [COL3])
    VALUES
    	('TEST1', 'english', 3),
    	('TEST2', 'english', 3),
    	('TEST3', 'english', 3)
    ;

**Query 1**:

    SELECT
            param
          , max(case when col1 = 'TEST1' then col3 end) AS test1
          , max(case when col1 = 'TEST2' then col3 end) AS test2
          , max(case when col1 = 'TEST3' then col3 end) AS test3
    FROM Input
    CROSS JOIN (SELECT 'COL2' AS param UNION ALL SELECT 'COL3' AS param) cj
    GROUP BY
            param
    

**[Results][2]**:
    
    | PARAM | TEST1 | TEST2 | TEST3 |
    |-------|-------|-------|-------|
    |  COL2 |     3 |     3 |     3 |
    |  COL3 |     3 |     3 |     3 |



  [1]: http://sqlfiddle.com/#!3/b84060/5

Open in new window

0
 

Author Comment

by:Raj G
ID: 40341651
Is there a way I can have 'english' value also in the result set?
0
 
LVL 49

Accepted Solution

by:
PortletPaul earned 2000 total points
ID: 40343229
You need to ensure that each column is a data type that can deal with the source data, so here I have converted col3 to varchar; but this is only because it appears col3 is an integer, if it already a (n)varchar then the conversion would not be needed.
SELECT
        param
      , max(case when col1 = 'TEST1' and param = 'COL2' then col2 
                 when col1 = 'TEST1' and param = 'COL3' then cast(col3 as varchar) end) AS test1
      , max(case when col1 = 'TEST2' and param = 'COL2' then col2 
                 when col1 = 'TEST2' and param = 'COL3' then cast(col3 as varchar) end) AS test2
      , max(case when col1 = 'TEST3' and param = 'COL2' then col2 
                 when col1 = 'TEST3' and param = 'COL3' then cast(col3 as varchar) end) AS test3
FROM Input
CROSS JOIN (SELECT 'COL2' AS param UNION ALL SELECT 'COL3' AS param) cj
GROUP BY
        param
;

Open in new window

| PARAM |   TEST1 |   TEST2 |   TEST3 |
|-------|---------|---------|---------|
|  COL2 | english | english | english |
|  COL3 |       3 |       3 |       3 |

http://sqlfiddle.com/#!3/b84060/10

Open in new window

0

Featured Post

Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

Question has a verified solution.

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

After restoring a Microsoft SQL Server database (.bak) from backup or attaching .mdf file, you may run into "Error '15023' User or role already exists in the current database" when you use the "User Mapping" SQL Management Studio functionality to al…
Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…

721 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