Click here to Skip to main content
15,898,597 members
Articles / Programming Languages / SQL
Tip/Trick

Pivot Table Using Linq Entity and SQL Server 2008 R2 for Dynamic Columns

Rate me:
Please Sign up or sign in to vote.
4.75/5 (6 votes)
20 Nov 2014CPOL 94.6K   15   16
How to create Pivot Table in SQL Server 2008 R2 and in C# Linq to Entity Framework in a step by step manner with two different instances.

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:

Image 1

And our expected output will be like below:

Image 2

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

Image 3

Dynamic Pivot Table Using C# and Linq Entity

C#
//
public DataTable GetPivotTableUsingLinqToEntity()
        {
            try
            {
                DataTable dt = new DataTable();
           
                using (var context = this.GetDataContext())
                {

		    //GetAllData() return All data for Student.
		
                    var data = context.GetAllData().ToList(); 

  		   // Student data will be like below

Image 4

C#
//Applying linq for geeting pivot output

            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();

   // By Using GetAllSubject() Method we will Get the list of all subjects

   var sub = context.GetAllSubject().ToList();
         // Distinct Subject Like Below

Image 5

C#
//Creating array for adding dynamic columns
        ArrayList objDataColumn = new ArrayList();

        if (data.Count() > 0)
        {
            //Three column are fix "rank","pupil","Total".
            objDataColumn.Add("Rank");
            objDataColumn.Add("Pupil");
            objDataColumn.Add("Total");

            //Add Subject Name as column in Datatable
            for (int i = 0; i < sub.Count; i++)
            {
                objDataColumn.Add(sub[i].SubName);
            }
        }
        //Add dynamic columns name to datatable dt
        for (int i = 0; i < objDataColumn.Count; i++)
        {
            dt.Columns.Add(objDataColumn[i].ToString());
        }

        //Add data into datatable with respect to dynamic columns and dynamic data
        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;
        //Now the Pivot datatable return like below screen

Image 6

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionAm I dreaming or you do a ToList before pivoting? Pin
Jaime Stuardo - Chile14-Jun-22 12:31
Jaime Stuardo - Chile14-Jun-22 12:31 
Questionpivot dynamic Pin
Elvally Boubacar25-Nov-17 7:05
Elvally Boubacar25-Nov-17 7:05 
PraiseReally appreciate this article Pin
phemmy samson25-Nov-16 0:06
phemmy samson25-Nov-16 0:06 
GeneralRe: Really appreciate this article Pin
Elvally Boubacar25-Nov-17 7:09
Elvally Boubacar25-Nov-17 7:09 
QuestionIn tip/trick: Pivot Table Using Linq Entity and SQL Server 2008 R2 for Dynamic Columns Pin
Member 124297283-May-16 2:16
Member 124297283-May-16 2:16 
this is not giving for me because some students not having score for some subject so it is fail for that and the data is coming different way
QuestionIf suppose one or more of the student(s) does not have entry for any of the subject this code FAILS... Pin
agam.makkar@thepsi.com22-Jun-15 19:21
agam.makkar@thepsi.com22-Jun-15 19:21 
QuestionCan you give me SQL Code Pin
Syed Mujahed18-Jun-15 19:36
Syed Mujahed18-Jun-15 19:36 
AnswerRe: Can you give me SQL Code Pin
Avinash Narnaware13-Jul-15 19:41
professionalAvinash Narnaware13-Jul-15 19:41 
Questionpivot with dynamic datas Pin
Member 1141805413-Apr-15 1:52
Member 1141805413-Apr-15 1:52 
SuggestionRe: pivot with dynamic datas Pin
Avinash Narnaware1-May-15 10:21
professionalAvinash Narnaware1-May-15 10:21 
GeneralThanks! Pin
tanya_kazak24-Feb-15 2:09
tanya_kazak24-Feb-15 2:09 
Questionpivot table Pin
fvv1121-Nov-14 20:35
fvv1121-Nov-14 20:35 
AnswerRe: pivot table Pin
Avinash Narnaware1-May-15 10:32
professionalAvinash Narnaware1-May-15 10:32 
GeneralRe: pivot table Pin
fvv111-May-15 20:28
fvv111-May-15 20:28 
GeneralMy vote of 5 Pin
Member 1125329321-Nov-14 4:21
Member 1125329321-Nov-14 4:21 
GeneralThank You Pin
Member 1125266321-Nov-14 0:09
Member 1125266321-Nov-14 0:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.