Invalid usage of aggregate function Sum() and Type: String

后端 未结 4 437
礼貌的吻别
礼貌的吻别 2020-12-21 15:25

I have a data table and a column contains int values. I have not specified the column with any datatype. When I perform the following.

object sum = dttest.Co         


        
相关标签:
4条回答
  • 2020-12-21 15:56

    When the program try it sum a datatable column which declared as string this error occur.
    Use the below code to make compute operation on string column.

    dtTable.Compute("Sum(Convert(" + col_Name + ", 'System.Int32')",""); 
    
    0 讨论(0)
  • 2020-12-21 15:57

    You can use LINQ to Datatable:

     var result = dttest.AsEnumerable()
                        .Sum(x => Convert.ToInt32(x["Value"]));
    

    Example how to Sum for specific name:

     var result = dttest.AsEnumerable()
                        .Where(r => r.Field<string>("Name") == "FilterName")
                        .Sum(x => Convert.ToInt32(x["Value"]));
    
    0 讨论(0)
  • 2020-12-21 15:58

    try

    dttest.Compute("Sum(Convert([Value], 'System.Int32'))","[Value] IS NOT NULL");
    
    0 讨论(0)
  • 2020-12-21 16:07

    try

    object sum = dttest.Compute("Sum(Value)", "[Value] IS NOT NULL");
    

    Sample code

        static DataTable GetTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("Value", typeof(int));
            table.Columns.Add("Name", typeof(string));
            table.Rows.Add(null, "a");
            table.Rows.Add(50, "a");
            table.Rows.Add(10, "a");
            table.Rows.Add(21, "b");
            table.Rows.Add(100, "b");
            return table;
        }
        static void Main(string[] args)
        {
            DataTable dt =GetTable();
            var str = dt.Compute("Sum(Value)", "Name='a' and Value is not null");
        }
    

    You can't Call Sum with Convert, but you can try below

    DataTable dt =GetTable();
    dt.Columns.Add("temp", typeof(int), "Convert(Value, 'System.Int32')");
    var str = dt.Compute("Sum(temp)", "Name='a' and Value is not null");
    
    0 讨论(0)
提交回复
热议问题