[英].group not returning all columns
I have a .group query that is not returning all the columns in the select and I was wondering if someone could validate my syntax. 我有一个.group查询,它没有返回select中的所有列,我想知道是否有人可以验证我的语法。 Here is a query with a .group and the result from my console;
这是一个带有.group的查询以及来自控制台的结果;
Expense.select('account_number, SUM(credit_amount)').group(:account_number).first
Expense Load (548.8ms) EXEC sp_executesql N'SELECT TOP (1) account_number, SUM(credit_amount) FROM [expenses] GROUP BY account_number'
(36.9ms) SELECT table_name FROM information_schema.views
Even though I select two columns, I'm only getting the first one to return. 即使我选择了两列,我也只能得到第一列。 I'm wondering if I may be dealing with an db adapter problem.
我想知道我是否正在处理数据库适配器问题。
Try giving your sum an alias: 尝试给您的总和一个别名:
expense = Expense.select('account_number, SUM(credit_amount) AS credit_amount').group(:account_number).first
puts expense.credit_amount
ActiveRecord doesn't create a default alias for aggregation operations such as SUM
, COUNT
etc... you have to do it explicitly to be able to access the results, as shown above. ActiveRecord不会为聚合操作(例如
SUM
, COUNT
等)创建默认别名。您必须显式地进行操作才能访问结果,如上所示。
The SUM(credit_amount)
column from the SQL has no alias and will not have a column name by default. SQL中的
SUM(credit_amount)
列没有别名,默认情况下将没有列名。 If you change it to have an alias SUM(credit_amount) As 'A'
for example and select the alias name, it should pick it up. 如果将其更改为具有别名
SUM(credit_amount) As 'A'
例如SUM(credit_amount) As 'A'
并选择别名,则应将其选中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.