Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8709677
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T04:25:25+00:00 2026-06-13T04:25:25+00:00

I have following function that converts normal DataTable to Pivot Table. But I have

  • 0

I have following function that converts normal DataTable to Pivot Table.

But I have 1 more requirement, it should also show Value column i.e sum of all the Pivot column cell.

e.g. : ORDER | SUM | PLANDATE
         1      50    10-Oct-2012
         1      10    10-Oct-2012
         2      15    12-Oct-2012

After PIVOT it should be like

ORDER | SUM | 10-Oct-2012 | 12-Oct-2012
  1      60     50            10
  2      15                   15

my pivot function is :

DataTable Pivot(DataTable dt, DataColumn pivotColumn, DataColumn pivotValue) {
    // find primary key columns 
    //(i.e. everything but pivot column and pivot value)
    DataTable temp = dt.Copy();
    temp.Columns.Remove( pivotColumn.ColumnName );
    temp.Columns.Remove( pivotValue.ColumnName );
    string[] pkColumnNames = temp.Columns.Cast<DataColumn>()
        .Select( c => c.ColumnName )
        .ToArray();

    // prep results table
    DataTable result = temp.DefaultView.ToTable(true, pkColumnNames).Copy();
    result.PrimaryKey = result.Columns.Cast<DataColumn>().ToArray();
    dt.AsEnumerable()
        .Select(r => r[pivotColumn.ColumnName].ToString())
        .Distinct().ToList()
        .ForEach (c => result.Columns.Add(c, pivotColumn.DataType));

    // load it
    foreach( DataRow row in dt.Rows ) {
        // find row to update
        DataRow aggRow = result.Rows.Find(
            pkColumnNames
                .Select( c => row[c] )
                .ToArray() );
        // the aggregate used here is LATEST 
        // adjust the next line if you want (SUM, MAX, etc...)
        aggRow[row[pivotColumn.ColumnName].ToString()] = row[pivotValue.ColumnName];
    }

    return result;
}

Thanks & any help will be appriciated…

Sample Data :
 OrderStatus    Qty     Dated
    New 100 10-Oct-2012
    New 150 10-Oct-2012
    New 100 10-Oct-2012
    Conf    200 12-Oct-2012
    New 100 12-Oct-2012
    Reconf  300 12-Oct-2012
    New 200 15-Oct-2012
    New 200 15-Oct-2012
    Reconf  100 18-Oct-2012
    New 150 18-Oct-2012
    Conf    150 18-Oct-2012
    New 100 20-Oct-2012
    Reconf  500 20-Oct-2012
    New 100 30-Oct-2012
    New 700 30-Oct-2012
    New 100 30-Oct-2012
    Conf    100 10-Oct-2012

Update Code :

 private DataTable DataTableToPivot(DataTable dtNormalTable, DataColumn pivotColumn, DataColumn valueColumn)
            {
                cTracing.WriteTrace("Inside DataTableToPivot", "DataTableToPivot");

                DataTable dtPivot = null;
                DataTable tempPivot = null;
                DataColumn sumColumn = new DataColumn();
                string[] pkColumnNames = null;

                try
                {
                    sumColumn.ColumnName = valueColumn.ColumnName;
                    sumColumn.DataType = typeof(string);
                    sumColumn.DefaultValue = "0";

var allrows = dt.AsEnumerable().Select(delegate(DataRow r)
            {
                DataRow nr = dt.NewRow();
                foreach (DataColumn item in dt.Columns)
                {
                    nr.SetField(item.ColumnName, r[item.ColumnName] is DBNull ? string.Empty : r[item.ColumnName]);
                }
                return nr;
            });

            dtNormalTable = allrows.CopyToDataTable();

                    // find primary key columns 
                    //(i.e. everything but pivot column and pivot value)
                    tempPivot = dtNormalTable.Copy();

                    tempPivot.Columns.Remove(pivotColumn.ColumnName);
                    tempPivot.Columns.Remove(valueColumn.ColumnName);

                    pkColumnNames = tempPivot.Columns
                                                 .Cast<DataColumn>()
                                                 .Select(c => c.ColumnName)
                                                 .ToArray();

                    // prep results table
                    dtPivot = tempPivot.DefaultView.ToTable(true, pkColumnNames).Copy();
                    dtPivot.PrimaryKey = dtPivot.Columns.Cast<DataColumn>().ToArray();
                    // include the sum column
                    dtPivot.Columns.Add(sumColumn);
                    try
                    {
                        dtNormalTable.AsEnumerable()
                          .Select(r => r[pivotColumn.ColumnName].ToString())
                          .Distinct()
                          .ToList()
                          .ForEach(c => dtPivot.Columns.Add(Convert.ToDateTime(c).ToString("dd-MMM-yyyy"), typeof(string)));
                    }
                    catch
                    {
                        dtNormalTable.AsEnumerable()
                          .Select(r => r[pivotColumn.ColumnName].ToString())
                          .Distinct()
                          .ToList()
                          .ForEach(c => dtPivot.Columns.Add(c, typeof(string)));
                    }

                    // load it
                    foreach (DataRow row in dtNormalTable.Rows)
                    {
                        // find row to update
                        DataRow aggRow = dtPivot.Rows.Find(
                            pkColumnNames
                                         .Select(c => row[c])
                                         .ToArray());
                        // the aggregate used here is LATEST 
                        // adjust the next line if you want (SUM, MAX, etc...)
                        string columnName = string.Empty;
                        try
                        {
                            columnName = Convert.ToDateTime(row[pivotColumn.ColumnName]).ToString("dd-MMM-yyyy");
                        }
                        catch
                        {
                            columnName = row[pivotColumn.ColumnName].ToString();
                        }

                        if (aggRow.IsNull(columnName))
                        {
                            aggRow[columnName] = Convert.ToDecimal(row[valueColumn.ColumnName]);
                        }
                        else
                        {
                            aggRow[columnName] = Convert.ToDecimal(aggRow[columnName]) +
                                                 Convert.ToDecimal(row[valueColumn.ColumnName]);
                        }

                        if (numberFormat == "3")
                        {
                            // add the value to the sum
                            aggRow[sumColumn] = (Convert.ToDecimal(aggRow[sumColumn].ToString()) +
                                                Convert.ToDecimal(row[valueColumn.ColumnName].ToString())).ToString("#0.000");
                        }
                        else if (numberFormat == "2")
                        {
                            // add the value to the sum
                            aggRow[sumColumn] = (Convert.ToDecimal(aggRow[sumColumn].ToString()) +
                                                Convert.ToDecimal(row[valueColumn.ColumnName].ToString())).ToString("#0.00");
                        }
                        else if (numberFormat == "1")
                        {
                            // add the value to the sum
                            aggRow[sumColumn] = (Convert.ToDecimal(aggRow[sumColumn].ToString()) +
                                                Convert.ToDecimal(row[valueColumn.ColumnName].ToString())).ToString("#0.0");
                        }
                        else
                        {
                            // add the value to the sum
                            aggRow[sumColumn] = (Convert.ToDecimal(aggRow[sumColumn].ToString()) +
                                                Convert.ToDecimal(row[valueColumn.ColumnName].ToString())).ToString("#0");
                        }
                    }

                    return dtPivot;
                }
                catch (Exception ex)
                {
                    cTracing.WriteTrace("Error inside DataTableToPivot", "DataTableToPivot");
                    cLogging.WriteLog(ex);
                    return null;
                }
                finally
                {
                    if (dtPivot != null)
                        dtPivot.Dispose();
                }
            }
enter code here
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T04:25:26+00:00Added an answer on June 13, 2026 at 4:25 am

    How about adding each row’s value to the sum column in the corresponding aggregate row?

    DataTable Pivot(DataTable dt, DataColumn pivotColumn, DataColumn pivotValue) {
        DataColumn sumColumn = new DataColumn();
        sumColumn.ColumnName = "SUM";
        sumColumn.DataType = typeof(int);
        sumColumn.DefaultValue = 0;
    
        // find primary key columns 
        //(i.e. everything but pivot column and pivot value)
        DataTable temp = dt.Copy();
        temp.Columns.Remove( pivotColumn.ColumnName );
        temp.Columns.Remove( pivotValue.ColumnName );
        string[] pkColumnNames = temp.Columns.Cast<DataColumn>()
            .Select( c => c.ColumnName )
            .ToArray();
    
        // prep results table
        DataTable result = temp.DefaultView.ToTable(true, pkColumnNames).Copy();
        result.PrimaryKey = result.Columns.Cast<DataColumn>().ToArray();
        // include the sum column
        result.Columns.Add(sumColumn);
        dt.AsEnumerable()
            .Select(r => r[pivotColumn.ColumnName].ToString())
            .Distinct()
            .OrderBy(c => Convert.ToDateTime(c))   // Order by the date
            .ToList()
            .ForEach (c => result.Columns.Add(c, pivotColumn.DataType));
    
        // load it
        foreach( DataRow row in dt.Rows ) {
            // find row to update
            DataRow aggRow = result.Rows.Find(
                pkColumnNames
                    .Select( c => row[c] )
                    .ToArray() );
            // the aggregate used here is LATEST 
            // adjust the next line if you want (SUM, MAX, etc...)
            string columnName = row[pivotColumn.ColumnName].ToString();
            if(aggRow.IsNull(columnName))
            {
                aggRow[columnName] = (int)row[pivotValue.ColumnName];          
            }
            else
            {
                aggRow[columnName] = Convert.ToInt32(aggRow[columnName]) +
                                     (int)row[pivotValue.ColumnName];
            }   
            // add the value to the sum
            aggRow[sumColumn] = (int)aggRow[sumColumn] + 
                                (int)row[pivotValue.ColumnName];
        }
    
        return result;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following function that works properly in Chrome and Firefox, but not
I have created user-defined function that converts a comma-delimited string into a table. I
I have the following as3 function below which converts normal html with links so
I have the following function that does string splitting: on splitText(aString, delimiter) set retVal
I have the following function that deletes the LaTeX command surrounding the current cursor
I have the following function that I am using to remove the characters \04
I have the following function that takes a number like 5 and creates a
I have the following function that retrieves an image from a twitter feed, the
I have the following function that is supposed to trigger anytime one of the
I have the following function that I only want to run inside <div id=imgWrapper>

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.