我正在尝试执行以下 hql查询。
String SQL_QUERY = "SELECT SUM(quantity) as sum FROM SalesDetails sd";
Query query = session.createQuery(SQL_QUERY);
for(Iterator it=query.iterate();it.hasNext();)
{
int row = Integer.parseInt((String) it.next());
System.out.print("MAX QUANTITY: " + row);
}
模型类中使用的“数量”的数据类型为字符串。但是当我尝试执行查询时,它会出错。
ERROR: ERROR: function sum(character varying) does not exist
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Position: 8
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet
请帮忙。如何在hibernate中对String值执行SUM函数。提前谢谢!
答案 0 :(得分:0)
如果您确定数量始终是一个数字,则在执行SUM之前将其强制转换为数字
所以
"SELECT SUM(to_number(quantity)) as sum FROM SalesDetails sd";
会将字符转换为数字,然后将其传递给SUM函数。
答案 1 :(得分:0)
你可以试试这个
select sum(cast(quantity as integer)) as sum FROM SalesDetails sd";
在求和函数之前,只需将其转换为整数。