MySQL计算列值的实例并按列值

时间:2017-07-11 16:43:16

标签: php mysql sql

我需要在一个表上进行相当高级的查询,该表包含客户发送的故障单,收集故障单的统计信息,以及按各种计数和/或列值排序和排序。

门票表:

+---------------------------+       
| 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 |
+---------------------------+

首先,我需要计算每件产品的门票总数。在这种情况下,product_id 1有3张票,product_id 2有5张票。然后,我需要获取issue列的值和每个列的出现次数。所以在这一点上,我期待这样的事情:

[
  '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
  ]
]

然后,我需要能够按每个问题的出现次数排序,例如:ORDER BY COUNT(missing-part)COUNT(broken-part)。在其他情况下,我只需要能够按问题数量而不是按问题值本身订购产品(因此按COUNT(issues)排序)。

谢谢!

2 个答案:

答案 0 :(得分:1)

yu可以使用subselect来计算product_id出现次数和主要选择用于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

答案 1 :(得分:1)

你可以通过两个级别的聚合来接近:

docker swarm init
docker swarm deploy -c mycomposefile.yml
docker-compose build
docker service update ...