Mysql 使用活动记录查询计算百分比

Mysql 使用活动记录查询计算百分比,mysql,ruby-on-rails,ruby,activerecord,Mysql,Ruby On Rails,Ruby,Activerecord,我有下面两张桌子 用户 UserID UserName UserCountry 1 User1 India 2 User2 India 3 User3 India 4 User4 China 5 User5 China 6 User6

我有下面两张桌子

用户

UserID UserName UserCountry 1 User1 India 2 User2 India 3 User3 India 4 User4 China 5 User5 China 6 User6 Brazil 7 User7 Brazil 8 User8 USA 9 User9 USA 10 User10 USA 我已经在SO和谷歌上彻底搜索过了,但还没有找到任何合适的答案。答案很接近,但即使这样对我也不起作用。

试试这个:

User.joins(:status).select("users.country AS user_country", "statuses.status AS user_status", "COUNT(*) AS count", "ROUND((COUNT(*)*100.0/(SELECT COUNT(*) FROM statuses WHERE status = 'Active')), 2) AS percentage").where("user_status = 'Active'").group("user_country")
你可以自己克隆来测试它

步骤如下:

  • 您需要加入
    用户
    状态
  • 接下来,您需要
    选择
    列-在本例中,我们选择2列<代码>国家
    (来自
    用户
    )和
    状态
    (来自
    状态
  • 为了便于显示,我添加了另一个名为
    count
    的专栏,告诉我们每个国家的活跃用户总数
  • 接下来,我们将每个国家和地区的总活跃用户数乘以100.0,再除以
    状态表中的总活跃用户数
  • 由于您只需要2位小数,我们需要使用
    舍入
    函数
  • 我们在一个长语句中使用数字4和5,并将结果列名别名为
    percentage
  • 我们还需要告诉ActiveRecord,我们只需要活动用户——看看
    where
    部分
  • 最后,我们需要按国家分组
  • 希望这有帮助

    更新

    结果示例:

    +----+--------------+-------------+-------+------------+
    | id | user_country | user_status | count | percentage |
    +----+--------------+-------------+-------+------------+
    |    | Brazil       | Active      | 7     | 20.59      |
    |    | China        | Active      | 9     | 26.47      |
    |    | India        | Active      | 11    | 32.35      |
    |    | USA          | Active      | 7     | 20.59      |
    +----+--------------+-------------+-------+------------+
    

    为什么您有一个单独的状态表?@在完整的状态表中,除了上面提到的之外,我们还有其他用户状态。例如,UserID 1是活动的,也是默认的。但是,即使它在同一个表中,我的查询的解决方案是什么。在您的查询中,百分比计算为(一个国家的总活跃用户)*100/(各国的总活跃用户),而我打算询问(一个国家的总活跃用户)*100/(该国家任何状态的总用户)。我试着临时提出你的问题,但没有得到答案。请你再试试看。
    @active_user = Status.where(UserStatus: “Active”).pluck(:UserID)
    @active_user_bycountry = User.group(:UserCountry).where(UserID: @user_active.to_a).count(:UserID)
    @total_user_bycountry = User.group(:UserCountry).count(:UserID)
    
    User.joins(:status).select("users.country AS user_country", "statuses.status AS user_status", "COUNT(*) AS count", "ROUND((COUNT(*)*100.0/(SELECT COUNT(*) FROM statuses WHERE status = 'Active')), 2) AS percentage").where("user_status = 'Active'").group("user_country")
    
    +----+--------------+-------------+-------+------------+
    | id | user_country | user_status | count | percentage |
    +----+--------------+-------------+-------+------------+
    |    | Brazil       | Active      | 7     | 20.59      |
    |    | China        | Active      | 9     | 26.47      |
    |    | India        | Active      | 11    | 32.35      |
    |    | USA          | Active      | 7     | 20.59      |
    +----+--------------+-------------+-------+------------+