Tuesday 6 May 2014

Convert Columns to Rows in Sql Server using Pivot

create table studentgrade
(
course char(1),
grade int
)

insert into studentgrade values('A',15),
                               ('A',17),
                               ('B',12),
                               ('C',10),
                               ('C',18),
                               ('C',1),
                               ('C',9)                   
                                   
select * from studentgrade
 
SELECT 
  Course,
  [1] AS 'Grade 1',
  [2] AS 'Grade 2',
  [3] AS 'Grade 3',
  [4] AS 'Grade 4'

 
FROM
(
  SELECT
    Course,
    Grade,
    ROW_NUMBER() OVER(PARTITION BY Course
                      ORDER BY COURSE) rownum
  FROM studentgrade
) t
PIVOT
(
   MAX(Grade)
   FOR rownum IN([1], [2], [3], [4])
) p;



Output:

C# LINQ Joins With SQL

There are  Different Types of SQL Joins  which are used to query data from more than one database tables. In this article, you will learn a...