PIVOT Table
- Pivot Table Using SQL Server 2008 R2
- Pivot Table Using C# and Linq Entity
Here, I am going to explain how to do Pivot table in SQL Server 2008 R2 in a step by step manner.
Pivot Table Using SQL Server 2008 R2
We have student data like below table:

And our expected output will be like below:

To achieve this kind of pivot table, we will write a stored procedure like below:

Dynamic Pivot Table Using C# and Linq Entity
public DataTable GetPivotTableUsingLinqToEntity()
{
try
{
DataTable dt = new DataTable();
using (var context = this.GetDataContext())
{
var data = context.GetAllData().ToList();

var d = ( from f in data
group f by new {f.Rank, f.Pupil, f.Total}
into myGroup
where myGroup.Count() > 0
select new
{ myGroup.Key.Rank,
myGroup.Key.Pupil,
myGroup.Key.Total,
subject = myGroup.GroupBy(f => f.Subject).Select
(m => new { Sub = m.Key, Score = m.Sum(c => c.Score)})
}).ToList();
var sub = context.GetAllSubject().ToList();

ArrayList objDataColumn = new ArrayList();
if (data.Count() > 0)
{
objDataColumn.Add("Rank");
objDataColumn.Add("Pupil");
objDataColumn.Add("Total");
for (int i = 0; i < sub.Count; i++)
{
objDataColumn.Add(sub[i].SubName);
}
}
for (int i = 0; i < objDataColumn.Count; i++)
{
dt.Columns.Add(objDataColumn[i].ToString());
}
for (int i = 0; i < d.Count; i++)
{
List<string> tempList = new List<string>();
tempList.Add(d[i].Rank.ToString());
tempList.Add(d[i].Pupil.ToString());
tempList.Add(d[i].Total.ToString());
var res = d[i].subject.ToList();
for (int j = 0; j < res.Count; j++)
{
tempList.Add(res[j].Score.ToString());
}
dt.Rows.Add(tempList.ToArray<string>());
}
return dt;

}
}
catch (Exception)
{
return null;
}
}
...