SQL C#如何获取具有特定属性的每条数据
本文关键字:属性 数据 何获取 获取 SQL | 更新日期: 2023-09-27 18:29:44
好的,我有一个评论表,每个评论都有一个评级和一个与正在评级的电影相关的电影ID。我在一部电影ID上加上多个评分,想得到评分的平均值。现在我只是试图计算评分的总数,但不幸的是,我只从数据库中得到了第一个输入的评分。我正试图将所有评级存储到ArrayList中,并计算总数,这是代码。。。
if (movieId > -1) { //if movie id was found
sql = "select Rating from Reviews where MovieID = '" + movieId + "';";
result.Close();
dbCmd.Connection = dbConn;
dbCmd.CommandText = sql;
result = dbCmd.ExecuteReader();
ArrayList total = new ArrayList();
int i = 0;
while (result.Read())
{
try
{
total.Add((int)result.GetInt16(i));
}
catch (System.IndexOutOfRangeException)
{
MessageBox.Show("Looping, total count: " + total.Count);
break;
}
MessageBox.Show("Looping, total count: " + total.Count);
i++;
}
if (total.Count > 0) //if total was calculated
{
//double avg = (double)result;
int computedTotal = 0;
foreach(int j in total)
{
computedTotal += j;
}
msg = "AVG Reviews successfully computed total result = " + computedTotal;
任何见解都将不胜感激。
正如梁所暗示的,如果您想要评分的总和,您可以将SQL查询更改为:
SELECT SUM(rating) AS totalRating FROM reviews WHERE movieid = 'What you want here'
这样,您就可以存储返回的int,而不必担心其他任何事情。我还想补充一点,如果你想得到平均值,你可以用AVG()聚合函数来代替它,比如:
SELECT AVG(rating) AS averageRating FROM reviews WHERE movieid = 'What you want here'
我还想补充一点,我建议您使用参数化查询,而不是像那样连接字符串。我认为你应该把前几行改成这样:
dbCmd.Connection = dbConn;
dbCmd.CommandText = "SELECT AVG(rating) AS averageRating FROM reviews WHERE movieID = @movieid";
dbCmd.CommandText.Parameters.AddWithValue("@movieid", movieId");
以下是有关聚合函数和参数化查询的信息。
根据我的理解,我认为这个SQL就是您所需要的:
sql = "select sum(Rating) from Reviews where MovieID = '" + movieId + "';";