2013-12-19 66 views
1

我在Rails應用程序有這樣的SELECT語句:Rails Active Record`group`:爲什麼這隻返回幾列?

... 
#<DailyStat subject: "Macroeconomics", topic: "Overview Of Economics", item_count: 160, correct_item_count: 0>, 
#<DailyStat subject: "Macroeconomics", topic: "Overview Of Economics", item_count: 1, correct_item_count: 0>, 
#<DailyStat subject: "Macroeconomics", topic: "Unemployment", item_count: 1, correct_item_count: 0>, 
#<DailyStat subject: "Macroeconomics", topic: "Inflation", item_count: 2, correct_item_count: 0>,... 

我得到這個,當我做一個基本的選擇這些列。現在,我的問題是,當我做daily_stats.select("subject, topic, sum(correct_item_count), sum(item_count)").group(:topic)聚集列至於item_counts和correct_item_counts結合起來,所得到的結果集爲:

#<DailyStat topic: "Demand And Consumer Behavior">, #<DailyStat topic: "Obligations">, #<DailyStat topic: "Computerized Auditing">, #<DailyStat topic: "Inflation">, #<DailyStat topic: "Overview Of Economics"> 

我失去了計數。這肯定只是某種語法問題,但我遇到了麻煩。我如何得到計數加起來?

回答

1

爲了在您的select子句中包含subject,還需要將其添加到group子句中。

daily_stats.select(
    "subject, topic, sum(correct_item_count), sum(item_count)" 
).group('topic, subject') 

當你執行這個查詢,你會看到輸出爲:

[#<DailyStat topic: "Demand And Consumer Behavior">, #<DailyStat topic: "Obligations">, #<DailyStat topic: "Computerized Auditing">, #<DailyStat topic: "Inflation">, #<DailyStat topic: "Overview Of Economics">] 

看不到sum(correct_item_count)sum(item_count)因爲它們不是模型的屬性的原因。

如果您檢查結果數組中某個對象的屬性,您將看到那裏的計數,但沒有密鑰。鑰匙將是空的。

嘗試:

daily_stats.select(
    "subject, topic, sum(correct_item_count), sum(item_count)" 
).group('topic, subject').first.attributes 

你可以別名既您sum(...)爲簡單起見。喜歡的東西如下:

daily_stats.select(
    "subject, topic, sum(correct_item_count) as total_correct_item_count, sum(item_count) as total_item_count" 
).group('topic, subject') 

該查詢會給你在每個結果對象的total_correct_item_counttotal_item_count屬性,所以你可以訪問它們爲:

daily_stats.select(
    "subject, topic, sum(correct_item_count) as total_correct_item_count, sum(item_count) as total_item_count" 
).group('topic, subject').first.total_correct_item_count 
+0

謝謝!但是,如何提取計數。我有一個後續問題。然後,我會如何將數組重新組織爲[subject] => [topic ...]? –

+0

@DaryllSantos,道歉,不知道我是否關注你。我建議你爲跟進問題創建一個新問題。我認爲最好儘可能將問題保留在一個特定的主題上。 – vee

+0

是的,當談到區分問題時你是對的。我要問的是按主題對結果行進行分組,但我已經解決了它。非常感謝你的回答,歡呼聲 –

0

計數的別名。它們將成爲返回對象的方法。

foos = foos.select("count(name) AS name_count").group(:bar)

foos.first.name_count # => something

Rails的可能使用的列名,你的數據庫讓當你不別名數,但如果它沒有我不無論如何要使用它作爲方法名。

+0

感謝您的回答,但即使有別名它仍然不輸出計數。 'daily_stats.select(「topic,count(correct_item_count)as foo」)。group(:topic)' –

相關問題