Top Group By DB2

后端 未结 2 2018
情深已故
情深已故 2021-01-27 03:56

I\'ve been trying for hours but can\'t get the query to do what I want using DB2. From table Company and Users I have the following tickets quantity info per company/user

<
2条回答
  •  面向向阳花
    2021-01-27 04:26

    This should work. Create a derived view to calculate the Quantity per user and per company. Then get the max of then Quantity and then join the max back to the the calculation of the quantity.

    SELECT p.company, 
           t.user, 
           t.quantity 
    FROM   (SELECT MAX(t.quantity) max_quantity, 
                   t.company 
            FROM   (SELECT  
                           COUNT(t.user) quantity, 
                           t.company 
                    FROM   ticket t 
                    GROUP  BY t.company) t) maxq 
           INNER JOIN (SELECT t.user, 
                              t.company, 
                              COUNT(t.user) quantity 
                       FROM   ticket t 
                       GROUP  BY t.company, 
                                 t.user) t 
             ON maxq.max_quantity = t.quantity 
                AND maxq.company = t.company 
           INNER JOIN company p 
             ON p.company = t.company 
    ORDER  BY t.quantity DESC 
    

    A working sample that shows the top users by tag for the StackOverflow data can be found here.

提交回复
热议问题