Click here to Skip to main content
15,909,539 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Here is my sql query through which i am generating a datatable
select user_id,Convert(char,date_of_travel,103) as date_of_travel,amount from booking where month(date_of_travel)='5' union select user_id,Convert(char,date_of_travel,103) as date_of_travel,amount from sight_seeing where month(date_of_travel)='5' order by user_id

VB
user_id date_of_travel amount
   101    01/05/2012   1000
   101    02/05/2012   500
   101    05/05/2012   700
   102    11/05/2012   800
   103    02/05/2012   850


Now i want to run this following query over this datatable
SELECT user_id,SUM(amount) FROM table GROUP BY user_id


Please help me to solve this.
Thanks in advance.
Posted

The solution 1 by mr.priyank is good.

Alternatively the Field extension method of DataRow explained here http://msdn.microsoft.com/en-us/library/bb360891.aspx[^] and CopyToDataTable extension method of IEnumerable explained here http://msdn.microsoft.com/en-us/library/bb359707[^] can be used as follows:
C#
DataTable data = new DataTable("Data");
data.Columns.Add("UserId",typeof(string),null);
data.Columns.Add("DateOfTravel",typeof(DateTime),null);
data.Columns.Add("Amount",typeof(double),null);

Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("hi-IN");
data.Rows.Add("101",DateTime.Parse("01/05/2012"),1000);
data.Rows.Add("101",DateTime.Parse("02/05/2012"),500);
data.Rows.Add("101",DateTime.Parse("05/05/2012"),700);
data.Rows.Add("102",DateTime.Parse("11/05/2012"),800);
data.Rows.Add("103",DateTime.Parse("02/05/2012"),850);

DataTable groupedData = new DataTable("GroupedData");
groupedData.Columns.Add("UserId",typeof(string),null);
groupedData.Columns.Add("Sum",typeof(double),null);

data.AsEnumerable().GroupBy (dr => dr.Field<string>("UserId"))
	.Select (dr => {
		DataRow row = groupedData.NewRow();
		row["UserId"]=dr.Key;
		row["Sum"] = dr.Sum (d => d.Field<double>("Amount"));
		return row;
	}).CopyToDataTable(groupedData,LoadOption.OverwriteChanges);
//groupedData
//UserId Sum
//101   2200 
//102    800 
//103    850
 
Share this answer
 
v2
C#
// let dt has the data from the database

System.Data.DataTable dtGroupedResult = new DataTable();
            dtGroupedResult.Columns.Add("userid");
           dtGroupedResult.Columns.Add("sumamount", typeof(Decimal));

            dt.AsEnumerable().GroupBy(e => e["userid"]).Select(e => new { userid = e.Key, sumammount = e.Sum(t => Convert.ToDecimal(t["amount"])) }).ToList().ForEach(e => { dtGroupedResult.Rows.Add(e.userid, e.sumammount); });
 
Share this answer
 
v2
Comments
sahabiswarup 22-May-12 9:15am    
thank you
VJ Reddy 3-Jun-12 0:33am    
Good answer. 5!

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900