按mysql中的列计算总行数和分组数

时间:2017-08-21 16:38:48

标签: mysql

所以我一直在看这个,我似乎无法弄明白。

我有一个包含以下格式和示例数据的mysql表:

ID, Customer, Time, Error Code, Duration

1,Test1,00:12:00,400,120
2,Test2,00:14:00,404,60
3,Test1,00:15:00,404,120
4,Test2,00:17:00,503,120
5,Test1,00:19:00,400,60
6,Test1,00:20:00,400,60
7,Test2,00:21:00,503,60

我需要结果包含客户名称,每个客户名称的总行数,每个客户的错误代码,然后是每个客户的错误数量,然后将持续时间相加。因此,对于上述结果,我希望得到:

Test1, 4, 400, 3, 360
Test1, 4, 404, 1, 360
Test2, 2, 404, 1, 240
Test2, 2, 503, 2, 240

我遇到的问题是当我按错误代码分组时,行数的计数和持续时间的总和也按错误代码分组。我需要客户的总行数和持续时间,而不是每个错误代码的客户总行数和持续时间。

如果我需要包含任何其他内容,或者我可能非常混淆,请告诉我。

提前感谢您的所有帮助!

2 个答案:

答案 0 :(得分:1)

首先,您需要分组来获取计算列

 SELECT Customer, COUNT(*) as total_count, SUM(duration) as total_duration
 FROM yourTable
 GROUP BY  Customer

 SELECT Customer, Error, COUNT(*) as error_count
 FROM yourTable
 GROUP BY  Customer, Error

然后加入你的表

SELECT t1.Customer, 
       t2.total_count, 
       t1.error, 
       t3.error_count, 
       t2.total_duration
FROM yourTable as t1
JOIN (
     SELECT Customer, COUNT(*) as total_count, SUM(duration) as total_duration
     FROM yourTable
     GROUP BY  Customer
     ) as t2
  ON t1.Customer = t2.Customer
JOIN (
     SELECT Customer, Error, COUNT(*) as error_count
     FROM yourTable
     GROUP BY  Customer, Error
) as t3
 ON t1.Customer = t3.Customer
AND t1.Error = t3.Error
GROUP BY t1.Customer
       , t1.Error

答案 1 :(得分:0)

您可以在子选择中使用连接与客户的总和 您可以在子选择中使用连接,并使用客户总和

select a.customer, a.error, t.num_row, t.duration 
from my_table   a
inner join ( 
    select  customer, count(*) as num_row, sum(duration) duration 
    from my_table 
    group by customer 
  ) t on t.customer  = a.customer