[英]distinct with multiple columns and then group by one - rails, mysql
I have a dataset that gives the underlying output to the underlying query:我有一个数据集,将底层 output 提供给底层查询:
Analyze
.where(some_conditions)
.joins(category: [category_subs: :sub])
.select('user_id, product_id, category_subs.sub_id as sub_id, is_successful, category_subs.level as level')
+---------+-------------+---------------+--------+-------------+
| user_id | product_id | is_successful | sub_id | level |
+---------+-------------+---------------+--------+-------------+
| 3223 | 20441 | 1 | 56 | 14 |
| 3223 | 20441 | 1 | 72 | 22 |
| 3223 | 20441 | 1 | 20 | 22 |
| 3223 | 20443 | 1 | 20 | 14 |
| 3223 | 20443 | 1 | 20 | 22 |
| 3223 | 20443 | 1 | 25 | 6 |
| 3223 | 20443 | 1 | 7 | 22 |
| 3223 | 20444 | 1 | 20 | 14 |
| 3223 | 20444 | 1 | 20 | 22 |
| 3223 | 20444 | 1 | 25 | 6 |
| 3223 | 20444 | 1 | 7 | 22 |
| 3223 | 20445 | 0 | 20 | 14 |
| 3223 | 20445 | 0 | 20 | 22 |
| 3223 | 20445 | 0 | 25 | 6 |
| 3223 | 20445 | 0 | 7 | 22 |
| 3223 | 20448 | 1 | 20 | 14 |
| 3223 | 20448 | 1 | 20 | 22 |
| 3223 | 20448 | 1 | 25 | 6 |
| 3223 | 20448 | 1 | 7 | 22 |
| 3223 | 20449 | 1 | 20 | 14 |
| 3223 | 20449 | 1 | 4 | 2 |
| 3223 | 20449 | 1 | 24 | 14 |
+---------+-------------+---------------+--------+-------------+
All i want from that data is success by sub category with ignoring the level attribute.我从该数据中想要的只是忽略级别属性的子类别成功。
I have tried this, but it doesn't work as i expected:我已经尝试过了,但它并没有像我预期的那样工作:
Analyze
.where(some_conditions)
.joins(category: [category_subs: :sub])
.group('sub_id')
.select('user_id, product_id, category_subs.sub_id as sub_id, sum(is_successful=0)')
Output the output that did not give the result I wanted: Output output 没有给出我想要的结果:
+--------+----------------------+
| sub_id | sum(is_successful=1) |
+--------+----------------------+
| 4 | 1 |
| 7 | 3 |
| 20 | 8 |
| 24 | 1 |
| 25 | 3 |
| 56 | 1 |
| 72 | 1 |
+--------+----------------------+
Expected output should be:预期的 output 应该是:
+--------+----------------------+
| sub_id | sum(is_successful=1) |
+--------+----------------------+
| 4 | 1 |
| 7 | 3 |
| 20 | 5 |
| 24 | 1 |
| 25 | 3 |
| 56 | 1 |
| 72 | 1 |
+--------+----------------------+
I can get the data in ruby way, but i need it in the ActiveRecord::Relation instance.我可以以 ruby 方式获取数据,但我需要ActiveRecord::Relation实例。
select
t.sub_id,
count(*)
from (
select sub_id
from f
where is_successful = 1
group by
product_id,
sub_id
order by sub_id
) t
group by t.sub_id;
That might work.那可能行得通。 You can use ActiveRecord
from
to create the inner query for the from statement and then use that result in the outer select.您可以使用 ActiveRecord
from
为 from 语句创建内部查询,然后在外部 select 中使用该结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.