我正在尝试根据玩家的高分创建排行榜。
每位玩家的得分随机输入数据库。
我需要根据他们的高分对他们进行排序,并对他们进行排名。
这里我想在datagridview中显示player_ID,player_name,player_nick和HP。
任何帮助表示赞赏。
string query1 =" SELECT player_ID'玩家ID',player_name'播放器 名字',player_nick'尼克姓名',HP'高分'来自player_profile ORDER 通过HP DESC";
到目前为止我的工作,我不知道如何排名
答案 0 :(得分:0)
以下代码将数据添加到dataGridView,然后在最后回答您的问题。
// Add columns to the dataGridView
dataGridView1.Columns.Add("player_ID", "player_ID");
dataGridView1.Columns.Add("player_name", "player_name");
dataGridView1.Columns.Add("player_nick", "player_nick");
dataGridView1.Columns.Add("HP", "HP");
// Add some data to the dataGridView
object[] rowData = new object[dataGridView1.Columns.Count];
rowData[0] = 0; // Player_ID
rowData[1] = "Pancho"; // Player_Name
rowData[2] = "Speedy"; // Player Nick
rowData[3] = Convert.ToDecimal("58.7"); // HP
dataGridView1.Rows.Add(rowData);
rowData[0] = 1;
rowData[1] = "Ramon";
rowData[2] = "Sleepy";
rowData[3] = Convert.ToDecimal("39.6"); // HP
dataGridView1.Rows.Add(rowData);
rowData[0] = 2;
rowData[1] = "Cimitrio";
rowData[2] = "Grumpy";
rowData[3] = Convert.ToDecimal("41.2"); // HP
dataGridView1.Rows.Add(rowData);
rowData[0] = 3; // Player_ID
rowData[1] = "Panfilo"; // Player_Name
rowData[2] = "Gummy Bear"; // Player Nick
rowData[3] = Convert.ToDecimal("61.5"); // HP
dataGridView1.Rows.Add(rowData);
// Sort dataGridView by HP
dataGridView1.Sort(dataGridView1.Columns[3], ListSortDirection.Ascending);
// Add rank column
dataGridView1.Columns.Add("Rank", "Rank");
// Rank players
for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
{
dataGridView1.Rows[i].Cells["Rank"].Value = Convert.ToString(i+1);
}
答案 1 :(得分:0)
您可以使用SQL为排名提供用户变量(我认为还有一些Rank()函数)。来自Workbench:
SET @rank=0;
SELECT Name, HP, @rank:=@rank+1 As Rank FROM Demo ORDER BY HP ASC
您也可以通过一个小的更改从代码中执行此操作:
string SQL = @"SET @rank=0;
SELECT Name, HP, StartDate, @rank:=@rank+1 As Rank
FROM Demo ORDER BY HP DESC;";
using (MySqlConnection dbcon = mySqlDB.GetMySQLConnection())
using (MySqlCommand cmd = new MySqlCommand(SQL,dbcon))
{
dbcon.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
dgv1.DataSource = dt;
}
结果:
http://www.json.org/javadoc/org/json/JSONObject.html
表中没有Rank列,它是通过上面的SQL语句添加的。
如果你有联系,它会变得更复杂。您必须引入一些其他变量来跟踪HP / Score何时更改并仅在@rank时增加。如果你想跳过关系排名({1,2,2,4} vs {1,2,2,3}),你还需要添加一个计数器。
一件事是您必须允许可以在连接字符串中指定的用户变量:
Server=SvrAddr;Database=myDB;Uid=myUsr;Pwd=myPass;Allow User Variables=True";
Connection Strings显示了如何跳过必须初始化rank
var:
string SQL = @"SELECT Name, HP, StartDate, @rank:=@rank+1 As Rank
FROM Demo, (SELECT @rank := 0) r ORDER BY HP DESC;";
添加(SELECT @rank := 0) r
可以防止必须明确声明它。很酷。