def to_sql
sql = StringIO.new String.new(""), "w"
sql << "SELECT #{ extended_values } FROM #{ @indices.join(', ') }"
sql << " WHERE #{ combined_wheres }" if wheres?
sql << " #{group_prefix} #{escape_columns(@group_by)}" if !@group_by.nil?
unless @order_within_group_by.nil?
sql << " WITHIN GROUP ORDER BY #{escape_columns(@order_within_group_by)}"
end
sql << " HAVING #{@having.join(' AND ')}" unless @having.empty?
sql << " ORDER BY #{escape_columns(@order_by)}" if !@order_by.nil?
sql << " #{limit_clause}" unless @limit.nil? && @offset.nil?
sql << " #{options_clause}" unless @options.empty?
sql.string
end