SQL AVG() 函数在多列时返回 INT
Posted
技术标签:
【中文标题】SQL AVG() 函数在多列时返回 INT【英文标题】:SQL AVG() function returns INT when multiple columns 【发布时间】:2016-02-28 10:54:08 【问题描述】:编辑:我写错了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】:正如您所指出的,您尝试在此查询中匹配 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
【讨论】:
试试新的解决方案? 不,我尝试了放置 CAST 的所有可能性,但仍然不起作用,看着您的解决方案,您会认为它会起作用,但仍然想知道为什么它不起作用。 你能做SELECT * FROM Users, Answers WHERE Users.Username = ?
并将结果放在问题中吗?
我试图了解如何查看 eclipse 的结果。因为我是在 servlet 中编写这些。知道如何查看结果吗?
看过一个 youtube 视频,几分钟后会发布结果。以上是关于SQL AVG() 函数在多列时返回 INT的主要内容,如果未能解决你的问题,请参考以下文章
当没有动态列时,将多列和多行的列连接成一个 varchar 值
LINQ to SQL语句Count/Sum/Min/Max/Avg操作符