sql - How to find top usage of IP pairs in PostgreSQL? -
i have table source_ip , destination_ip , usage. want find top usage ip pairs. table this:
source_ip | destination_ip | usage 192.168.1.1 | 192.168.1.2 | 20 192.168.1.2 | 192.168.1.1 | 30 192.168.1.3 | 192.168.1.2 | 20 192.168.1.2 | 192.168.1.3 | 20
for example 2 records 1 pair.
source_ip | destination_ip | usage 192.168.1.1 | 192.168.1.2 | 20 192.168.1.2 | 192.168.1.1 | 30
finally want this
192.168.1.1 , 192.168.1.2 used 50 b 192.168.1.2 , 192.168.1.3 used 40 b
this query,
with t1 as( select source_ip, distination_ip, sum(usage) receiver group source_ip, distination_ip ) select distinct * t1 join t1 t2 on t1.source_ip = t2.distination_ip , t1.distination_ip = t2.source_ip
and query return this:
source_ip | destination_ip | usage | source_ip | destination_ip | usage 192.168.1.1 | 192.168.1.2 | 20 | 192.168.1.2 | 192.168.1.1 | 30 192.168.1.2 | 192.168.1.1 | 30 | 192.168.1.1 | 192.168.1.2 | 20 192.168.1.3 | 192.168.1.2 | 20 | 192.168.1.2 | 192.168.1.3 | 20 192.168.1.2 | 192.168.1.3 | 20 | 192.168.1.3 | 192.168.1.2 | 20
you can make arbitrary decision represent the "smaller" ip address first , "larger" second. there on, it's simple group by
, sum
:
with t1 ( select least(source_ip, distination_ip) ip1, greatest(source_ip, distination_ip) ip2 , usage receiver ) select ip1, ip2, sum(usage) t1 group ip1, ip2
or, if want result formatting in query itself:
with t1 ( select least(source_ip, distination_ip) ip1, greatest(source_ip, distination_ip) ip2 , usage receiver ) select ip1 || ' , ' || ip2 || ' used ' || sum(usage) || ' b' t1 group ip1, ip2
Comments
Post a Comment