需要简单的Postgres查询嵌套选择查询

时间:2016-09-22 10:14:38

标签: sql postgresql

connection_table

    app   | src_port  | dst_port |  src_ip  | dst_ip  | time  | L1  | L2  
----------+-----------+----------+----------+---------+-------+-----+----
    HTTP  | 100       | 200      |  x       | y       |  t1   | 1   | 0    
    HTTPS | 101       | 300      |  x       | y       |  t1   | 1   | 0  
    HTTP  | 102       | 200      |  a       | b       |  t2   | 0   | 1  
    HTTP  | 100       | 200      |  x       | y       |  t2   | 1   | 0
    HTTP  | 100       | 200      |  x       | y       |  t3   | 1   | 0
    HTTP  | 111       | 200      |  x       | y       |  t4   | 1   | 0

结果

    app   | sum(L1)  | sum(L2)  
----------+----------+--------
    HTTP  | 2        | 1  
    HTTPS | 0        | 1

查询

select app_table.app, 
       SUM(app_table.L1), 
       SUM(app_table.L2) 
from (
   select app, L1, L2 
   from connection_table 
   group by app, src_port, dst_port, src_ip, dst_ip
) as app_table 
group by app_table.app;

以上查询用于获取结果。我需要一个没有嵌套选择的查询?
这里,src_port,dst_port,src_ip和dst_ip唯一标识一个应用程序。需要计算每个应用的总L1和L2。

1 个答案:

答案 0 :(得分:0)

使用分组依据

注意:您的输出似乎有误。

SELECT
    app,
    SUM(L1) AS L1,
    SUM(L2) AS L2
FROM connection_table T
GROUP BY T.app  

<强>输出:

enter image description here

相关问题