Mysql 使用活动记录查询计算百分比
我有下面两张桌子 用户 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和谷歌上彻底搜索过了,但还没有找到任何合适的答案。答案很接近,但即使这样对我也不起作用。试试这个: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
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
的专栏,告诉我们每个国家的活跃用户总数状态表中的总活跃用户数
舍入
函数percentage
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 |
+----+--------------+-------------+-------+------------+