0

I'm using SQL in pgadmin4 (Postgres). I query a list of IP's and occurences of the IP's. If it matches the regex I want to print the regex and the sum of occurences.

I'm querying the following:

select distinct dstaddress, _col1 from test where _col1 > 1 AND 
dstaddress LIKE '10.228.55.%' OR 
dstaddress LIKE '10.228.9.%' 
group by dstaddress, _col1

And this gives me as output the IP and its occurences:

"10.228.55.17"  365942
"10.228.9.104"  8
"10.228.9.105"  4
"10.228.9.106"  2
"10.228.9.107"  8
"10.228.9.108"  10
"10.228.9.109"  434
"10.228.9.110"  127

But as output I want to have the regex and the sum of occurences:

"10.228.55.%"   365942
"10.228.9.%"    593

How can I achieve this?

1 Answer 1

1

Here is one method:

select v.pat, sum(t._col1)
from (values ('10.228.55.%'), ('10.228.9.%')) v(pat) left join
     test t
     on t._col1 > 1 and
        t.dstaddress like v.pat
group by v.pat;

Note: "occurrences" appears to be _col1. You would, of course, use whatever the appropriate column is, if that is not the case.

This puts the patterns in the derived table. They can then be used for the aggregation, without having to repeat them (a source of errors in the query).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.