相关疑难解决方法(0)

如何在同一个select语句中使用count和group by

我有一个具有group by的sql select查询.我想在group by语句后计算所有记录.有没有办法直接从sql?例如,拥有一个包含用户的表我想选择不同的城镇和用户总数

select town, count(*) from user
group by town
Run Code Online (Sandbox Code Playgroud)

我想要一个包含所有城镇的列,另一个列包含所有行中的用户数.

有3个城镇和58个用户的结果示例如下:

Town         Count
Copenhagen   58
NewYork      58
Athens       58
Run Code Online (Sandbox Code Playgroud)

sql group-by count

211
推荐指数
5
解决办法
65万
查看次数

GroupingError:错误:列""必须出现在GROUP BY子句中或用于聚合函数

我正在尝试创建一份留下评论的独特患者名单.代码字很好,直到我上传到heroku,它在postgresql中不起作用.

这是我创建列表的Ruby .erb代码:

<% @comments.group(:patient_id).each_with_index do |comment, index| %>
    <div class="profile-post color-one">
       <span class="profile-post-numb"><%= index+1 %></span>
        <div class="profile-post-in">
            <h3 class="heading-xs"><a><%= link_to "#{comment.patient.first_name} #{comment.patient.last_name}", comment_path(comment) %></a></h3>
            <p>Lastest comment from <%= time_ago_in_words(comment.created_at) %> ago<i class="pull-right"><%= link_to "Edit", edit_comment_path(comment) %> <%= link_to "Delete", comment_path(comment), method: :delete, data: {confirm: 'Are you sure you want to delete'} %></i></p>
        </div>
    </div>
<% end %>
Run Code Online (Sandbox Code Playgroud)

@comments在控制器中定义为:

def index
  @comments = current_clinician.comments.order("created_at desc")
end
Run Code Online (Sandbox Code Playgroud)

heroku日志给我这个错误信息:

PG::GroupingError: ERROR:  column "comments.id" must appear in the GROUP BY clause or be …
Run Code Online (Sandbox Code Playgroud)

ruby postgresql group-by ruby-on-rails heroku

4
推荐指数
1
解决办法
2635
查看次数

标签 统计

group-by ×2

count ×1

heroku ×1

postgresql ×1

ruby ×1

ruby-on-rails ×1

sql ×1