Click here to Skip to main content
15,912,082 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
CSS
CODE      NAME          AMT       PER
480530    TESTASSET1    100.00    2.00
480530    TESTASSET2    200.00    2.00
480535    TESTASSET3    300.00    5.00
480535    TESTASSET4    400.00    5.00


Im using a table named T_TEST..In a datagridview im showing records of unique codes only as given below..
CSS
 CODE      NAME          AMT       PER
480530    TESTASSET1    100.00    2.00
480535    TESTASSET3    300.00    5.00

But i have to sum the amount of unique codes and show it as one record as given below...
CSS
 CODE      NAME          AMT       PER
480530    TESTASSET1    300.00    2.00
480535    TESTASSET3    700.00    5.00


pls give me query for that...

[Edit] : fixed formatting
Posted
Updated 3-May-12 4:59am
v2

1 solution

The following LINQ query can be used to sum the amounts for each code and populate a DataTable, which can be assigned to the DataSource property of DataGridView
C#
//Let us say the Data is read into a DataTable from the SQL DB
//The following code is given here only to run the sample
DataTable ttest = new DataTable();
ttest.Columns.Add("Code",typeof(long),null);
ttest.Columns.Add("Name",typeof(string),null);
ttest.Columns.Add("Amt",typeof(decimal),null);
ttest.Columns.Add("Per",typeof(double),null);
ttest.Rows.Add(480530,"TESTASSET1",100.00,2.00);
ttest.Rows.Add(480530,"TESTASSET2",200.00,2.00);
ttest.Rows.Add(480535,"TESTASSET3",300.00,5.00);
ttest.Rows.Add(480535,"TESTASSET4",400.00,5.00);
//The code upto here is given only to run sample

DataTable uniqueCodes = ttest.Clone();

ttest.AsEnumerable().GroupBy (t => t.Field<long>("Code")).Select (row => 
{DataRow uRow = uniqueCodes.NewRow();
 		uRow[0]=row.Key;
		DataRow gRow = row.FirstOrDefault ();
		uRow[1]=gRow[1];
		uRow[3]=gRow[3];
		uRow[2]=row.Sum (r => r.Field<decimal>("Amt"));
		return uRow;
}
).CopyToDataTable(uniqueCodes,LoadOption.OverwriteChanges);
//The uniqueCodes can be assigned to the DataGridView
dataGridView1.DataSource = uniqueCodes;
//The contents of uniqueCodes will be
//Code  Name        Amt Per 
//480530 TESTASSET1 300 2 
//480535 TESTASSET3 700 5 


[Edit] SQL Query to sum amt, added [/Edit]

SQL
SELECT CODE, NAME, SUM(AMT) AS AMT, PER
FROM T_TEST
GROUP BY CODE
 
Share this answer
 
v4
Comments
premkumar.r 3-May-12 10:16am    
SRY SIR..ONE MORE SUGGESTION..IM HAVING 'N' NUMBER OF RECORDS IN MY TABLE..I WANT AN SQL QUERY TO SUM THE AMOUNT HAVING UNIQUE CODES
VJ Reddy 3-May-12 10:37am    
Please see the updated solution. I have added the SQL Query.
Sandeep Mewara 4-May-12 10:02am    
Good answer. 5!
VJ Reddy 4-May-12 10:16am    
Thank you, Sandeep.

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