rails 3: trying to COUNT/GROUP on multiple fields, but getting SQL error
My table StoreCodes holds uniqu开发者_Go百科e products codes (and their availablity) for each store, eg:
category:integer
code:string
available:boolean
store_id:reference
I'm trying to show a simple table with 3 columns showing how many codes are in each category, AND how many of those codes have available = true
Category_number / Count_Codes_in_category / Count_Codes_in_category_available==TRUE
In my controller, the following attempt to COUNT and GROUP on both category
and available
throws this error:
SQLite3::SQLException: near "WHERE": syntax error: SELECT category, available, COUNT(*) AS instances GROUP BY category, available WHERE (store_id = 8)
My controller code:
@b2 = StoreCode.find_by_sql ['SELECT category, available, COUNT(*) AS instances GROUP BY category, available WHERE (store_id = ?)', @store.id]
Your SQL is wrong. You have to put the GROUP BY
clause after the WHERE
clause, and when using find_by_sql
you also need to write the complete statement (include the FROM
clause)
Like this:
@b2 = StoreCode.find_by_sql ['SELECT category, available, COUNT(*) AS instances
FROM store_codes WHERE (store_id = ?) GROUP BY category, available', @store.id]
Your SQL statement has no 'FROM' clause, I also think the 'GROUP BY' should come after the 'WHERE'.
精彩评论