SQL percentage aggregation over group by clause

时间:2015-04-23 05:43:56

标签: mysql sql

I have a table that gives the following sql query inputs gives.

select server, count(*) from ServerNames where server is not null and server != '' and timestamp >= '2015-03-18'
and timestamp <= '2015-04-19' group by server;

Server | Count(*)
_________________
Server1    1700  
Server2    1554

select server, ip_address, count(*) from serverNames where server is not null and server != '' and ip_address is not null and ip_address != '' and timestamp >= '2015-03-18'
and timestamp <= '2015-04-19'  group by server, ip_address;

Server |    ip_address      | count(*)
______________________________________
Server1  Sample_ip_1            14
Server2  Sample_ip_2           209
Server1  Sample_ip_2           100
Server1  Sample_ip_1            50

I am finding difficulty in writing a query that calculates percentage within the group . So for instance in my example the output should be.

Server | ip_address | Count(*) | percent
________________________________________________
Server1  Sample_ip_1  14         0.82% (14/1700)
Server2  Sample_ip_2 209         13.44%(209/1554)
Server1  Sample_ip_2 100         5.88%(100/1700)
Server2  Sample_ip_1  50         3.217(15/1554)

How can I write a query to do that?

2 个答案:

答案 0 :(得分:1)

您只需要将两个查询的结果加在一起,然后concat将一堆内容加在一起,以获得您正在寻找的percent值。我认为应该这样做。

select q2.server, q2.ip_address, concat(round((q2.c / q1.c) * 100, 2), '%(', q2.c, '/', q1.c, ')') as percent 
  from
    (
      select server, count(*) c 
        from ServerNames 
        where server is not null 
          and server != '' 
          and timestamp >= '2015-03-18'
          and timestamp <= '2015-04-19' 
        group by server
     ) q1
     inner join
     (
       select server, ip_address, count(*) c  
         from serverNames 
         where server is not null 
           and server != '' 
           and ip_address is not null 
           and ip_address != '' 
           and timestamp >= '2015-03-18'
           and timestamp <= '2015-04-19'  
         group by server, ip_address
     ) q2
     on q1.server = q2.server

demo here

答案 1 :(得分:0)

为了这个例子,我将建议分别选择每个查询到中间表A和B.我不知道count(*)值代表什么,所以我将分别称它们为分子和分母。

SELECT
    A.Server, B.ip_address, B.numerator, (B.numerator * 100.0) / A.denominator
FROM A
INNER JOIN B ON A.Server = B.Server