Counting total rows and grouping by a column in mysql

后端 未结 2 1883
萌比男神i
萌比男神i 2021-01-28 19:38

So i\'ve been looking at this one for a while and I can\'t seem to figure it out.

I have a mysql table with the following format and sample data:

ID, Cus         


        
相关标签:
2条回答
  • 2021-01-28 20:02

    You could use a join on a subselect with the sum for customer You could use a join on a subselect with the sum for customer

    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
    
    0 讨论(0)
  • 2021-01-28 20:13

    First you need group by to get the calculated columns

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

    and

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

    Then join back to you table

    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
    
    0 讨论(0)
提交回复
热议问题