【发布时间】:2014-08-15 17:39:04
【问题描述】:
我有一个 User 模型和一个 Workplace 模型。用户有一个字段性别(男/女),每个工作场所都有很多用户。我想选择工作场所中的用户总数,以及按工作场所名称分组的工作场所的女性用户总数。
这是我尝试过的。
User.select("workplaces.name as workplace_name, count(*) as FTE, (count(case when users.gender='m' and users.created_at BETWEEN date_trunc('month', now()) and now() then 1 end)::float - count(case when users.gender='f' and users.created_at BETWEEN date_trunc('month', now()) and now() then 1 else null end)::float)/100 as ratio").joins("INNER JOIN workplaces on workplaces.id=users.workplace_id").group(:workplace_name).order("ratio desc").limit(5).map(&:attributes)
上述查询获取工作场所中的男性和女性用户并计算(女性 - 男性)/100。 我得到比率作为正值和负值。
如何只选择计算比率的正值/负值
谢谢
【问题讨论】:
-
到目前为止,我从计算的比率中得到了正值和负值。如何只选择正比率值?
-
如
ABS? -
@pozs 可以使用。但是比率不是表格上的字段/列。那么如何使用呢?拥有(“比率> 0”)不起作用
-
没有 negative ratio 这样的东西。也没有理由将一个比率除以 100。如果你想要一个 比率,那就是
female/male。如果您想要百分比,则为female/totalEmployees。你要哪个?它看起来接近百分比差异,但也不适合。
标签: mysql sql postgresql ruby-on-rails-4