SQL AVG()函数在多列时返回INT

时间:2016-02-28 10:54:08

标签: java sql jdbc derby

编辑:我写错WHERE Users.Username=?而不是WHERE Answers.Username=?时出错了

<小时/> 如果我使用以下语句,我得到正确的平均值3.33:

public final String SELECT_USER_AND_AVGANSWERS_STMT =
"SELECT AVG(CAST(Answers.Rating AS FLOAT)) FROM Answers "
+ "WHERE Answers.Username=?";

注意我只选择AVG。当我尝试选择更多列时,它返回4,就像它将其四舍五入一样。

public final String SELECT_USER_AND_AVGANSWERS_STMT = 
"SELECT Users.Username, Users.Nickname, AVG(CAST(Answers.Rating AS FLOAT)) "
+ "FROM Users, Answers "
+ "WHERE Users.Username=?"
+ "GROUP BY Users.Username, Users.Nickname";

用户表:

"CREATE TABLE Users(Username VARCHAR(10) PRIMARY KEY,"
+ "Password VARCHAR(8) NOT NULL,"
+ "Nickname VARCHAR(20) NOT NULL,"
+ "Description VARCHAR(50),"
+ "Photo VARCHAR(4000))";

答案表:

"CREATE TABLE Answers(AnswerID INTEGER PRIMARY KEY GENERATED ALWAYS AS IDENTITY,"
+ "QuestionID INTEGER NOT NULL,"
+ "SubmittedTime TIMESTAMP NOT NULL,"
+ "Text VARCHAR(300) NOT NULL,"
+ "Username VARCHAR(10) NOT NULL,"
+ "Rating INTEGER DEFAULT 0 NOT NULL)";

使用Java / Embedded Derby数据库。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

正如您所指出的,您尝试匹配此查询中的Users.Username,但是在第一个查询中匹配Answers.Username,这是一个问题!这应该有效:

SELECT Users.Username, Users.Nickname, AVG(CAST(Answers.Rating AS FLOAT))
FROM Users, Answers
WHERE Answers.Username=?
GROUP BY Users.Username, Users.Nickname

其他可能有问题的是聚合是否发生在CAST之前。要检查这一点,您可以使用:

SELECT UserName, NickName, CAST(AVG(AnswersRating) AS FLOAT)
FROM
(
    SELECT Users.Username As UserName, Users.Nickname As NickName, CAST(Answers.Rating AS FLOAT) As AnswersRating
    FROM Users, Answers
    WHERE Answers.Username=?
) AS Float_Table
GROUP BY UserName, NickName