2015-04-23 131 views
0

我有一张表,它给出了以下sql查询输入给出的内容。按分组划分的SQL百分比聚合条款

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 

我在编写计算组内百分比的查询时遇到困难。因此,例如在我的例子中,输出应该是。

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) 

我该如何编写一个查询来做到这一点?

+0

第二次输出的计数(*)/第一次计数(*)。 – station

+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

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