[英]MySQL counting instances of column values and sorting by column value
I have a rather advanced query I need to do on a table that holds trouble tickets sent in by customers, to gather statistics about the tickets, and to order and sort by various counts and/or column values. 我有一个相当高级的查询,我需要在一个表上进行保存客户发送的故障单,收集有关故障单的统计信息以及按各种计数和/或列值进行排序和排序。
Tickets table: 门票表:
+---------------------------+
| product_id | issue |
+------------|--------------+
| 1 | missing-part |
| 1 | missing-part |
| 1 | broken-part |
| 2 | broken-part |
| 2 | broken-part |
| 2 | missing-part |
| 2 | missing-part |
| 2 | missing-part |
+---------------------------+
First, I need to count the total number of tickets per product. 首先,我需要计算每种产品的门票总数。 In this case,
product_id 1
has 3 tickets and product_id 2
has 5 tickets. 在这种情况下,
product_id 1
有3张票,而product_id 2
有5张票。 Then, I need to get the values of the issue
column and the number of occurrences of each. 然后,我需要获取
issue
列的值以及每个值的出现次数。 So at this point, I'm expecting something like this: 所以在这一点上,我期望这样的事情:
[
'product_id' => 1,
'issues' => 3
'issue_nums' => [
'missing-part' => 2,
'broken-part' => 1
]
],
[
'product_id' => 2,
'issues' => 5,
'issue_nums' => [
'missing-part' => 3,
'broken-part' => 2
]
]
Then, I need to be able to order by the number of of occurrences of each issue, for example: ORDER BY COUNT(missing-part)
or COUNT(broken-part)
. 然后,我需要能够按每个问题的出现次数进行排序,例如:
ORDER BY COUNT(missing-part)
或COUNT(broken-part)
。 In other cases, I just need to be able to order the products by number of issues in total rather than by the issue values themselves (so ordering by COUNT(issues)
). 在其他情况下,我只需要能够按总问题数而不是问题值本身来订购产品(因此,按
COUNT(issues)
订购)即可。
Thanks! 谢谢!
yu could use a subselect for count product_id occurence and a main select for issuse yu可以使用subselect来计数product_id的出现,并使用main select来进行issuse的计数
select t1.product_id, t2.product_count, t1.issue, count(*) count_issue
from Tickets t1
inner join (
select product_id, count(*) product_count
from Tickets
group by product_id) t2 on t2.product_id = t1.product_id
group by t1.product_id, t2.product_count, t1.issue
order by count_issue
You can come pretty close with two levels of aggregation: 您可以非常接近两个聚合级别:
select t.product_id, sum(cnt) as total,
group_concat(issue, ':', cnt separator ',') as issues
from (select t.product_id, t.issue, count(*) as cnt
from tickets t
group by t.product_id, t.issue
) tp
group by t.product_id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.