1

Hi I changed my database from mySql to PostgreSQL and get an error every time I use query with :order statement

For example the following code works perfectly in MySQL

Hour.sum("working_hours",:conditions=>['project_id=? AND reported_date=?',project,h.reported_date],:order=>"reported_date

But gives me an error in PostgreSQL

PGError: ERROR: column "hours.reported_date" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ...rted_date='2010-10-06 00:00:00.000000') ORDER BY reported_d..
: SELECT sum("hours".working_hours) AS sum_working_hours FROM "hours" WHERE (project_id=1 AND reported_date='2010-10-06 00:00:00.000000') ORDER BY reported_date

If I delete the order statement then the query works ok
I will most appreciate any help on this subject

1 Answer 1

2

PostreSQL is stricter to the SQL standard than MySQL is.

SQL states that if you ORDER by a column, that column must be SELECTed and appear in the GROUP BY clause.

Try this:

Hour.sum("working_hours",:conditions=>['project_id=? AND reported_date=?',project,h.reported_date], :order=>"reported_date", :group_by => "working_hours"
Sign up to request clarification or add additional context in comments.

2 Comments

This query actually returns an ordered hash of sums, grouped by reported_date. If he wanted a sum of all working hours, this will not give him the correct answer.
PGError: ERROR: column "hours.reported_date" must appear in the i tried it but i still get an error GROUP BY clause or be used in an aggregate function LINE 1: ...:00:00.000000') GROUP BY working_hours ORDER BY reported_d...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.