2016-06-28 24 views
2

我有這個非常簡單的SQL查詢,我試圖在我的rails控制檯中執行。在rails應用程序中原始pg GROUP BY查詢

SELECT name, manual_score FROM objectives GROUP BY manual_score 

但它拋出一個錯誤是:

ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: column "objectives.name" must appear in the GROUP BY clause or be used in an aggregate function 

我已經使用欄前面加上表的名字嘗試,但仍然是錯誤。任何幫助都會變得渺茫。謝謝!

回答

2

問題是,您列出的是未分組的列。您應該將name添加到GROUP BY或從選擇中刪除它。

SELECT name, manual_score FROM objectives GROUP BY name, manual_score 
-- OR 
SELECT manual_score FROM objectives GROUP BY manual_score 
-- OR 
SELECT COUNT(name), manual_score FROM objectives GROUP BY manual_score 

你爲什麼要列添加到您的group by或使用聚合函數?想象一下,你有以下數據:

name  | manual_score 
one  | 1 
two  | 1 
three  | 2 

現在,試着族元素由manual_score和思考如何顯示符合manual_score=1name列。

+0

This Works !!感謝您的快速回復和解釋。 – titan