Sort Datatable and Rank Using ratio
-
09-12-2019 - |
Pregunta
I have a query where i get some columns from database it is simple select statement then I add columns to this datatable as :
dt.Columns.Add(new DataColumn("ratio", typeof(double)));
Then I have another column called Rank which is again added manually as follow :
dt.Columns.Add(new DataColumn("Rank", typeof(int)));
now how do I first of all sort by ratio and then add rank using the ratio e.g. the higher the ratio the higher the rank for example if ratio is 3, 5 and 9 once ordered by ratio it should be :
rank ratio
1 9
2 5
3 3
EDIT :
the ratio is calculated by dividing the two columns in my query
foreach (DataRow row in dt.Rows)
{
row["Ratio"] = (Convert.ToDecimal(row["LastMonth"]) / NoOfBranches).ToString("0.##");
}
Thanks
Solución
If you want to do this from the C# side of the world:
DataTable dt = new DataTable();
dt.DefaultView.Sort = "ratio DESC";
dt.Columns.Add(new DataColumn("Rank", typeof(int)));
int count = 1;
foreach (DataRowView dr in dt.DefaultView)
{
dr["Rank"] = count++;
}
Whenever using the DataTable, you need to refer to dt.DefaultView as it is the sorted version of the table. See the MSDN for more info:
http://msdn.microsoft.com/en-us/library/system.data.datatable.defaultview.aspx
Otros consejos
Using the information and the restrinctions you have given us, I'll suggest the next code:
dt.Columns.Add(new DataColumn("Ratio", typeof(double)));
dt.Columns.Add(new DataColumn("Rank", typeof(int)));
foreach (DataRow row in dt.Rows)
{
row["Ratio"] =
(Convert.ToDecimal(row["LastMonth"]) / NoOfBranches).ToString("0.##");
}
//sorting the DataTable using the new DataColumn
dt.DefaultView.Sort = "Ratio DESC";
//after the sort, set the rank for each one
int rank = 1;
foreach (DataRow row in dt.Rows)
{
row["Rank"] = rank++;
}
Example extracted from forum post.
Direct from db:
SELECT RANK() OVER (ORDER BY ratio DESC) AS rank,ratio FROM [YourTableName]